I suspect you may have enabled the strict
or strictNullChecks
flag in your compiler config (either through the command line when you call tsc
or in the tsconfig.json
file).
In strict null checking mode, the null and undefined values are not in the domain of every type and are only assignable to themselves and any (the one exception being that undefined is also assignable to void).
[1]
As an example we can reproduce this using this sample code,
let ids: string[] = [];
let x: string | undefined;
x = Math.random() > 0.5 ? undefined : 'hello';
ids.push(x);
Here the compiler can't tell if x
will be undefined
or a string
. (Note if you do x = 'hello'
, then the compiler can statically check that x
is not undefined
at runtime)
We'll compile this with the strict
flag enabled (which also enables the strictNullChecks
flag)
We get the following compiler error
src/main.ts:4:10 - error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.
4 ids.push(x);
~
So you may want to either define the ids
variable as (string | undefined)[]
as another answer suggests or consider disabling the strict flags.
Another possible solution is to use the !
(
Non-null assertion operator) operator to bypass the compiler (but you're intentionally ignoring a potential bug in many situations by using this since the compiler can no longer help you),
ids.push(x!);
let ids: (string | undefined)[] = [];