It seems bizarre to me that while undefined
and null
are compatible with void
, the reverse is not true, considerably eroding the utility of optional parameters:
function getThing(): string | void {}
function checkThing(val: string = 'abcd') {}
checkThing(getThing())
t.ts(3,12): error TS2345: Argument of type 'string | void' is not assignable to parameter of type 'string'.
Type 'void' is not assignable to type 'string'.
Specifying an optional arg without default value doesn't change the error, but specifying a union with void
does (and generates that with default-initialize the parameter as expected). It seems rather onerous to insist on declaring a void
union on all optional parameters that may at any point in time be the target of the result of a void function. What else would you do with a void
parameter?
Your code sample:
function getThing(): string | void {}
function checkThing(val: string = 'abcd') {}
checkThing(getThing())
t.ts(3,12): error TS2345: Argument of type 'string | void' is not assignable to parameter of type 'string'.
Type 'void' is not assignable to type 'string'.
Focus in on the error Type 'void' is not assignable to type 'string'
. checkThing
expects a string
and is given something that you said could be void
. Hence the error.
It seems rather onerous to insist on declaring a void union on all optional parameters that may at any point in time be the target of the result of a void function. What else would you do with a void parameter?
This is by design from the TypeScript team. You are entitled a different opinion and I can sympathise with your desires 🌹
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.