【问题标题】:Can I define array of strings and undefined in typescript?我可以在打字稿中定义字符串数组和未定义的数组吗?
【发布时间】:2019-02-21 16:44:33
【问题描述】:

我在 typescript 中定义了以下数组:let ids: string[] = [];。然后,当我尝试推送一个 id(可能未定义)时,我遇到了编译错误:ids.push(id); 给了我以下编译错误:

TS2345:类型参数“字符串”| undefined' 不能分配给“字符串”类型的参数。类型“未定义”不可分配给类型“字符串”。

我可以创建字符串数组和未定义的数组吗?

【问题讨论】:

  • let ids: (string | undefined)[] = [];
  • 你的 tsconfig 是什么样的?

标签: typescript


【解决方案1】:

是的:

let ids: (string | undefined)[] = [];

【讨论】:

  • 我认为这不能解决根本问题。 OP 可能启用了导致此行为的严格编译器标志。
【解决方案2】:

我怀疑您可能在编译器配置中启用了strictstrictNullChecks 标志(通过调用tsc 时的命令行或在tsconfig.json 文件中)。

在严格的 null 检查模式下,null 和 undefined 值不在每种类型的域中,并且只能分配给它们自己和任何类型(一个例外是 undefined 也可以分配给 void)。 [1]

作为一个例子,我们可以使用这个示例代码重现这个,

let ids: string[] = [];
let x: string | undefined;
x = Math.random() > 0.5 ? undefined : 'hello';
ids.push(x);

这里编译器无法判断xundefined 还是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)[],或者考虑禁用严格标志。

另一种可能的解决方案是使用! ( Non-null assertion operator) 运算符来绕过编译器(但在许多情况下,你故意忽略了一个潜在的错误,因为编译器不能再帮助你了),

ids.push(x!);

【讨论】:

    猜你喜欢
    • 2019-07-11
    • 2022-06-28
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 2019-12-07
    • 2011-07-01
    • 1970-01-01
    相关资源
    最近更新 更多