15

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?

2
  • 2
    let ids: (string | undefined)[] = [];
    – JLRishe
    Feb 21, 2019 at 16:47
  • What does your tsconfig looks like?
    – francium
    Feb 21, 2019 at 16:48

2 Answers 2

25

Yes:

let ids: (string | undefined)[] = [];
2
  • I don't think this answers the underlying issue. OP might have enabled the strict compiler flag which is resulting in this behavior.
    – francium
    Feb 21, 2019 at 16:57
  • Rolled back the previous suggested edit to this answer as it doesn't work in latest Typescript (4.7) & even if it did, would've been different: [string] | undefined rather than [string|undefined].
    – RickN
    Jul 4, 2022 at 14:07
3

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!);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.