I have defined the following array in typescript: let ids: string[] = [];
. Then when I try to push an id (which might be undefined) I have a compilation error: ids.push(id);
gives me the following compilation error:
TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.
Can I create array of strings and undefined?
TypeScript knows that the find() method returns the first value in the array for which the condition was satisfied, or undefined if the condition is never satisfied. If we exclude undefined from the possible values the result variable stores, the compiler can be sure the variable is an object.
In TypeScript, an array is an ordered list of values. An array can store a mixed type of values. To declare an array of a specific type, you use the let arr: type[] syntax.
Sometimes the TypeScript compiler isn't able to determine what type of value it may at a certain point. By adding the exclamation mark ( ! ) at the end, you let the TypeScript compiler that there is no way this variable will be undefined or null.
To check for undefined in TypeScript, use a comparison to check if the value is equal or is not equal to undefined , e.g. if (myValue === undefined) {} or if (myValue !== undefined) {} . If the condition is met, the if block will run.
Yes:
let ids: (string | undefined)[] = [];
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!);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With