【发布时间】:2021-09-16 21:24:31
【问题描述】:
我想根据提供给工厂方法的实例参数创建实例。我能够使用重载编写以下代码。 如何使用 TypeScript 泛型来表达?
class Car {
brand = 'Skoda';
}
class Human {
name = 'Jan';
}
class Garage {
lots = 5;
}
class House {
floors = 2;
}
class NotAllowed {
anything = 'anything';
}
class Selection {
pick(what: Car) : Garage;
pick(what: Human) : House;
pick(what: any) : any {
if (what instanceof Car) {
return new Garage();
} else if (what instanceof Human) {
return new House();
} else {
throw Error('Not supported')
}
}
}
const selection = new Selection();
selection.pick(new Car()).lots; // compiler successfully autocompletes
selection.pick(new Human()).floors // compiler successfully autocompletes
selection.pick(new NotAllowed()); // compiler error
【问题讨论】:
标签: typescript generics overloading typescript-generics