输入'T |undefined' 不能分配给类型 'T'.'T' 可以用与 'T | 无关的任意类型实例化.不明确的'
警告:TypeScript 菜鸟问题.
WARNING: TypeScript noob question.
我正在通过 Udemy 学习 TypeScript (https://www.udemy.com/专业课程/打字稿).在尝试一些示例代码时,我在代码中遇到错误:
I am learning TypeScript via Udemy (https://www.udemy.com/course/typescript-for-professionals). While trying some sample code I get an error in Code:
class Queue4<T> {
private data: Array<T> = [];
push( item: T ):void { this.data.push(item) }
pop( ):T { return this.data.shift() } // error: Type 'T | undefined' is not assignable to type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to 'T | undefined'.ts(2322)
}
const myQueue4 = new Queue4<number>();
myQueue4.push( 123 )
myQueue4.push( 234 )
console.log( myQueue4.pop().toPrecision(1) )
对此错误的其他搜索无济于事 - 样本太复杂.我遇到的最有用的事情是@jcalz 的解释:
Other searches on this error don't help -- samples are too complex. The most useful thing I have come across is this explanation from @jcalz:
TypeScript 中的泛型函数充当表示其泛型类型参数的所有可能规范的函数,因为指定类型参数的是函数的调用者,而不是实现者.
Generic functions in TypeScript act as a function representing every possible specification of its generic type parameters, since it's the caller of the function that specifies the type parameter, not the implementer.
'R' 可以使用与 'Response
即使我在类 TS 仍然抱怨之后删除代码.对于目标":es5"和目标",我都遇到了相同的错误.和目标":es2015".
Even if I remove the code after the class TS still complains. I get the same error for both "target": "es5" and "target": "es2015".
- 为什么会这样?
- 我该如何解决这个问题?
第一个选项:
class Queue4<T> {
private data: Array<T> = [];
push(item: T): void {
this.data.push(item)
}
pop(): T {
// At runtime shift() should return undefined in case of empty array.
// That's why, if you want to return T you should tell TS to exclude undefined from resulting type
// by means of ! operator
return this.data.shift()!;
}
}
第二种选择:
class Queue4<T> {
private data: Array<T> = [];
push(item: T): void {
this.data.push(item)
}
pop(): T | undefined {
// At runtime shift() should return undefined in case of empty array.
// That's why ypou should declare union nullable type T | undefined as a resulting type
return this.data.shift();
}
}
const myQueue4 = new Queue4<number>();
// And here you should explicitly check the result to refine type
const result = myQueue4.pop();
if (result) {
console.log(result.toPrecision(1));
}