我在TypeScript中有这个非常简单的代码:
"Alex mona ok"
在具体课程中,当我将type SomeType = [number, number, number]; // Should be an array of exactly 3 numbers
interface IThing {
someThing: SomeType
}
abstract class SomeClass {
abstract getThing(): IThing;
}
class ConcreteClass extends SomeClass {
getThing() {
return {
someThing: [4, 2, 2];
}
}
}
分配给someThing
时,Typescript会抱怨[4, 2, 2]
。为什么这样,以及如何确保Type number[] is not assignable to type [number, number, number]
只是一个包含3个数字的数组?
答案 0 :(得分:1)
如果你在回报中输入了类型注释,它可以正常工作:
type SomeType = [number, number, number]; // Should be an array of exactly 3 numbers
interface IThing {
someThing: SomeType
}
abstract class SomeClass {
abstract getThing(): IThing;
}
class ConcreteClass extends SomeClass {
getThing(): IThing { // annotation here
return {
someThing: [4, 2, 2] // no error here
}
}
}
在没有类型注释的情况下,您将遇到以下情况:
type SomeType = [number, number, number]; // Should be an array of exactly 3 numbers
let x: SomeType;
// Okay
x = [1,2,3];
// Not okay
let y = [1,2,3]; // inferred `number[]`
x = y;
即。推断的返回类型与所需的3tupple类型不兼容。