【问题标题】:TypeScript - Type 'number | undefined' is not assignable to type 'number'TypeScript - 输入“数字”| undefined' 不可分配给类型 'number'
【发布时间】:2019-06-17 21:10:21
【问题描述】:

这是我的代码:

var a:number;
a = 4;

var myArr: number[];
myArr = [1,2,3];
myArr.push(1);

a = myArr.pop();

当我将“module”(在我的 tsconfig.json 文件中)设置为“system”或“amd”以允许我将输出捆绑到“outFile”位置进行编译时,我收到以下错误:

hello-world.ts:23:1 - 错误 TS2322: 键入 'number |未定义'不是 可分配给类型“数字”。类型“未定义”不可分配给 输入“数字”。

a = myArr.pop();

它从哪里获得“未定义”类型?另外,如何在不将“strict”设置为 false(在我的 tsconfig.json 中)的情况下解决此错误?

【问题讨论】:

  • .pop() 如果数组为空,则返回undefined

标签: typescript


【解决方案1】:

Array.prototype.pop() 返回类型号或未定义。这就是 number undefined 的来源。

对对象执行pop()时,array.length > 0时返回数字,array.length = 0时返回undefined。

您应该检查myArr.pop() !== undefined

-或-

a: number | undefined;

【讨论】:

  • 我有 !== undefined check in place,但仍然出现该错误:/
  • @jayarjo 提出的问题的任何解决方案?
  • @Nyxynyx a = myArr.pop() as number;
猜你喜欢
  • 2023-02-22
  • 1970-01-01
  • 2022-12-06
  • 2020-08-20
  • 1970-01-01
  • 2022-10-22
  • 1970-01-01
  • 2023-01-11
  • 2023-01-18
相关资源
最近更新 更多