// 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()] //打字稿将x推断为(House | Car)[]
以下行将由Typescript解释为[House,Car]类型的两个元素元组。
const x = [new House(), new Car()] // Typescript will infer x as (House|Car)[]
我知道,这有点令人困惑,因为两者都使用相同的语法,即[
和]
。
现在您可以稍微修改函数签名,以产生我认为更正确的键入。
function printHousesOrCars<T extends Printable[]>(...arr: T): void {
arr.forEach(item => item.print())
}
在呼叫站点上,以上将作为具有第一个参数House
和第二个Car
的函数进行解析。
printHousesOrCars(new House(), new Car()) // [House, Car]
PlaygroundMore on the rest parameters subject
我希望这是有道理的。 :)