// 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)[]
I cannot understand the last line, and if I wrote
const x = [new House(), new Car()] // Typescript will infer x as (House|Car)[]
HouseandCarhave the same structure, so the compiler sees them as the same type. You should distinguish them at the type level, say by adding incompatible properties, like amanufacturerproperty toCarand anumBathroomsproperty toHouse.function printHousesOrCars<T extends Printable[]>(...arr: T): void { //etc...?