[英]Can I define array of strings and undefined in typescript?
I have defined the following array in typescript: let ids: string[] = [];
我在打字稿中定义了以下数组:
let ids: string[] = [];
. . Then when I try to push an id (which might be undefined) I have a compilation error:
ids.push(id);
然后,当我尝试推送一个 id(可能未定义)时,出现编译错误:
ids.push(id);
gives me the following compilation error:给我以下编译错误:
TS2345: Argument of type 'string |
TS2345:“字符串”类型的参数 | undefined' is not assignable to parameter of type 'string'.
undefined' 不能分配给'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).我怀疑您可能在编译器配置中启用了
strict
或strictNullChecks
标志(通过调用tsc
时的命令行或在tsconfig.json
文件中)。
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).
在严格的空值检查模式下,空值和未定义值不在每种类型的域中,并且只能分配给它们自己和任何类型(一个例外是未定义也可以分配给 void)。 [ 1 ]
[ 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
.在这里,编译器无法判断
x
是undefined
还是string
。 (Note if you do x = 'hello'
, then the compiler can statically check that x
is not undefined
at runtime) (请注意,如果您执行
x = 'hello'
,则编译器可以静态检查x
在运行时是否undefined
)
We'll compile this with the strict
flag enabled (which also enables the strictNullChecks
flag)我们将在启用
strict
标志的情况下编译它(这也启用strictNullChecks
标志)
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.因此,您可能希望按照另一个答案的建议将
ids
变量定义为(string | undefined)[]
或考虑禁用严格标志。
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!);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.