类型 'number | undefined' 不可分配给类型 'number',打字稿错误?
Type 'number | undefined' is not assignable to type 'number', typescript error?
function example(queue: number[]): number[] {
const curLength: number = queue.length
for (let i = 0; i < curLength; i++) {
**const cur: number = queue.shift()**
};
}
错误是星号所在的位置。有一个 if 语句来检查 undefined 是多余的,因为看代码很清楚 cur
不能 undefined
因为我迭代了队列的长度。
在这种情况下,解决错误的正确做法是什么?
原因是 shift()
可以 return 元素 (a number
),或者 undefined
如果数组为空 (source). In this case, it has the signature shift() : number | undefined
. A good IDE, or the Typescript Playground,会告诉你这个。
编译器无法确定如果数组为空则不会执行该语句,因此它仍然考虑了 shift()
会 return [=14] 的情况=].但是,如果作为开发人员,您确信您的程序是正确的,您可以通过附加 !
( “non-null 断言运算符”,更多信息 here) 到有问题的表达式:
const cur: number = queue.shift()!;
要么,要么改变cur
的类型:
const cur : number | undefined = queue.shift();
function example(queue: number[]): number[] {
const curLength: number = queue.length
for (let i = 0; i < curLength; i++) {
**const cur: number = queue.shift()**
};
}
错误是星号所在的位置。有一个 if 语句来检查 undefined 是多余的,因为看代码很清楚 cur
不能 undefined
因为我迭代了队列的长度。
在这种情况下,解决错误的正确做法是什么?
原因是 shift()
可以 return 元素 (a number
),或者 undefined
如果数组为空 (source). In this case, it has the signature shift() : number | undefined
. A good IDE, or the Typescript Playground,会告诉你这个。
编译器无法确定如果数组为空则不会执行该语句,因此它仍然考虑了 shift()
会 return [=14] 的情况=].但是,如果作为开发人员,您确信您的程序是正确的,您可以通过附加 !
( “non-null 断言运算符”,更多信息 here) 到有问题的表达式:
const cur: number = queue.shift()!;
要么,要么改变cur
的类型:
const cur : number | undefined = queue.shift();