[英]Can I define array of strings and undefined in typescript?
我在打字稿中定义了以下数组: let ids: string[] = [];
. 然后,当我尝试推送一个 id(可能未定义)时,出现编译错误: ids.push(id);
给我以下编译错误:
TS2345:“字符串”类型的参数 | undefined' 不能分配给'string' 类型的参数。 类型“未定义”不可分配给类型“字符串”。
我可以创建字符串数组和未定义的数组吗?
是的:
let ids: (string | undefined)[] = [];
我怀疑您可能在编译器配置中启用了strict
或strictNullChecks
标志(通过调用tsc
时的命令行或在tsconfig.json
文件中)。
在严格的空值检查模式下,空值和未定义值不在每种类型的域中,并且只能分配给它们自己和任何类型(一个例外是未定义也可以分配给 void)。 [ 1 ]
作为一个例子,我们可以使用这个示例代码重现这个,
let ids: string[] = [];
let x: string | undefined;
x = Math.random() > 0.5 ? undefined : 'hello';
ids.push(x);
在这里,编译器无法判断x
是undefined
还是string
。 (请注意,如果您执行x = 'hello'
,则编译器可以静态检查x
在运行时是否undefined
)
我们将在启用strict
标志的情况下编译它(这也启用strictNullChecks
标志)
我们得到以下编译器错误
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);
~
因此,您可能希望按照另一个答案的建议将ids
变量定义为(string | undefined)[]
或考虑禁用严格标志。
另一种可能的解决方案是使用!
( 非空断言运算符)运算符绕过编译器(但您在许多情况下故意忽略潜在错误,因为编译器无法再帮助您),
ids.push(x!);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.