【发布时间】:2020-09-09 18:04:59
【问题描述】:
我有一个泛型函数,它的返回类型基于输入类型。如何根据提供的参数正确确保返回类型的类型安全?
示例
interface IKeyboardService{
type() : void;
}
class KeyboardService{
type(){
}
}
interface IMouseService{
move() : void;
}
class MouseService{
move(){
}
}
interface ServiceTypeMapping{
Keyboard: IKeyboardService,
Mouse: IMouseService
}
type ServiceType = keyof ServiceTypeMapping;
function getService<T extends ServiceTypeMapping, K extends keyof ServiceTypeMapping>(serviceType : K): typeof T[K]{
switch(serviceType){
case 'Keyboard':
return new KeyboardService();
case 'Mouse':
return new MouseService();
}
throw new Error("No implementation error");
}
//This should be an error
const mouseService = getService('Keyboard');
我正在传递键盘并期待 IKeyboardService。目前,这在 getService 的返回类型上出错。
你可以在这里玩:https://stackblitz.com/edit/typescript-leut1x
谢谢。
【问题讨论】:
-
您可以删除
T并只使用function getService<K extends keyof ServiceTypeMapping>(serviceType: K): ServiceTypeMapping[K] {但键入实现很棘手