【发布时间】:2020-04-21 15:54:34
【问题描述】:
// Generic Constraints
class Car {
print() {
console.log('I am a car')
}
}
class House {
print() {
console.log('I am a house')
}
}
interface Printable {
print(): void;
}
// tell Typescript that I promise the T type will satisfy the Printable interface
function printHousesOrCars<T extends Printable>(...arr: T[]): void {
arr.forEach(item => item.print())
}
printHousesOrCars(1, 2, 3) // This line went wrong,I can understand
printHousesOrCars(new House(), new Car()) // this line Typescript infer T[] is Car[], I cannot understand, why shouldn't it be (House|Car)[]
我看不懂最后一行,如果我写了
const x = [new House(), new Car()] // Typescript 会将 x 推断为 (House|Car)[]
【问题讨论】:
-
您的
House和Car具有相同的structure,因此编译器将它们视为相同的类型。你应该distinguish them at the type level,比如添加不兼容的属性,比如manufacturer属性到Car和numBathrooms属性到House。 -
如果你把你的函数改为:
function printHousesOrCars<T extends Printable[]>(...arr: T): void { //etc...呢? -
@jcalz 谢谢,这真的很有帮助。是不是意味着使用泛型,TS不会将类型推断为联合类型,它必须是特定类型。
-
@flavio 不起作用兄弟,那么 T[] 是一个二维数组
-
@crazyones110 它不限于二维数组。数组的长度实际上取决于您如何调用该函数。如果你用 10 个参数调用它,它会推断出一个有 10 个元素的元组。 Look this playground code
标签: typescript generics type-inference typescript-generics