I have a function expression that returns nothing. However, the following doesn't work.
let printHello: void = (): void => console.log('Hello!');
However, if I change the type to object
it works!
let printHello: object = () => console.log('Hello!');
I think I have the actual function under control. However, I can't seem to annotate the variable printHello
correctly...
A TS variable declaration always takes the same form:
let <name>[: <type>][ = <value>];
In your case:
let printHello: void = (): void => console.log('Hello!');
// name | type | value
(The function also has the : void
return type, but that's part of the value so not relevant here.)
However, the actual type of the value, which can be inferred if we remove the explicit type from the declaration:
let printHello = (): void => console.log('Hello!');
is not void
, it's () => void
- the value itself isn't undefined, it's a function returning undefined. So if you do want to explicitly include the type and not rely on inference (which "may add unnecessary verbosity"), it would have to be:
let printHello: () => void = (): void => console.log('Hello!');
// name | type | value
object
works not because your function returns an object (it doesn't), but because a function is an object.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments