简体   繁体   中英

Can I define array of strings and undefined in typescript?

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?

是的:

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM