[英]How to infer return type based on return type of function in parameters
[英]How can infer return type of a function using the parameters supplied?
我有一个通用的 function,其返回类型基于输入类型。 如何根据提供的参数正确确保返回类型的类型安全?
例子
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
谢谢你。
您可以使用重载:
function getService(serviceType: 'Keyboard'): KeyboardService;
function getService(serviceType: 'Mouse'): MouseService;
function getService(serviceType: keyof ServiceTypeMapping): ServiceTypeMapping[keyof ServiceTypeMapping] {
switch(serviceType){
case 'Keyboard':
return new KeyboardService();
case 'Mouse':
return new MouseService();
default:
throw new Error("No implementation error");
}
}
您还可以在返回时使用条件类型来执行此操作:
function getService<T extends ServiceType>(serviceType: T) {
let returnService
switch(serviceType){
case 'Keyboard':
returnService = new KeyboardService();
break;
case 'Mouse':
returnService = new MouseService();
break;
default:
throw new Error("No implementation error");
}
return returnService as T extends 'Keyboard' ? KeyboardService : MouseService
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.