打字稿 - 键入 'number | undefined' 不可分配给类型 'number'

dev*_*ost 5 typescript

这是我的代码:

var a:number;
a = 4;

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

a = myArr.pop();
Run Code Online (Sandbox Code Playgroud)

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

hello-world.ts:23:1 - 错误 TS2322:输入“数字” undefined' 不能分配给类型 'number'。类型 'undefined' 不能分配给类型 'number'。

a = myArr.pop();

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

gat*_*byz 6

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

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

你应该检查是否 myArr.pop() !== undefined

-或者-

a: number | undefined;

  • @Nyxynyx `a = myArr.pop() 作为数字`; (3认同)
  • 我已经 !== undefined 检查到位,但仍然收到该错误:/ (2认同)