在 Typescript 中使用泛型数组进行类型推断
Type inference with generic array in Typescript
// 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 will infer x as (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]
Playground
More on the rest parameters subject
我希望这是有道理的。 :)
// 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 will infer x as (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]
Playground More on the rest parameters subject
我希望这是有道理的。 :)