Description
TypeScript Version: 2.0.3
Code
With --strictNullChecks
:
let x: string | void = 'hello';
let y: string | void = undefined;
let z: string | void = null;
Expected behavior: compiles, since the documentation states:
However, when using the
--strictNullChecks
flag,null
andundefined
are only assignable tovoid
and their respective types.
https://www.typescriptlang.org/docs/handbook/basic-types.html#null-and-undefined
Actual behavior: the last line fails to compile:
[eval].ts (3,1): Type 'null' is not assignable to type 'string | void'. (2322)
Rationale: is there a less verbose way, with --strictNullChecks
, to specify a type like string | null | undefined
? i.e. Is there a type that covers both null
and undefined
?
Activity
mhegazy commentedon Oct 20, 2016
no. We could not find a way to do that that is not confusing to some users. see #7426.
if you really want to define something like this, i would recomend adding
aseemk commentedon Oct 20, 2016
Thanks for the quick answer and link!
So consider this issue just an issue to clarify the documentation then.
donaldpipowitch commentedon Mar 29, 2017
Just stumbled over this. I always thought that
void
would be a union type ofnull
andundefined
and wondered why this throws with--strictNullChecks
:So what is
void
exactly for--strictNullChecks
? Just an alias toundefined
?Any idea to add something like this to the
lib.*.d.ts
files? Or as:Or a real common union type for
null
andundefined
?type voidlike = null | undefined;
?aluanhaddad commentedon Mar 29, 2017
I think that an issue here is that while technically JavaScript doesn't have any notion of void functions, having void in the type system is actually useful catching certain logic errors.
That said, returning null from a void function absolutely needs to be a type error. Returning undefined and returning without a value result in the same runtime behavior. The caller gets undefined.
KaelWD commentedon Dec 20, 2018
Yet
void
cannot be assigned toundefined
Looks like there's more on this over at #20006
karlhorky commentedon Jun 24, 2019
Just found a similar issue #16075, will do a PR to fix the docs.
Edit: PR open: microsoft/TypeScript-Handbook#1053