Typescript中具有通用数组的类型推断

问题描述 投票:0回答:1
// 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 generics type-inference typescript-generics
1个回答
0
投票

以下行将由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

我希望这是有道理的。 :)

© www.soinside.com 2019 - 2024. All rights reserved.