我有一种将数组转换成各种类型的javascript对象的方法,这些类型的接口与以下类似:
export interface IService1 {
header: string;
desc: string;
serviceID: number;
...
}
export interface IService2 {
footer: string;
desc: string;
serviceID: number;
otherStuff: string;
...
}
export interface IService3 {
container: string;
desc: string;
serviceID: number;
otherStuff: string;
...
}
我的转换方法类似于:
function convArrayToObject(datatype: string, fields: string[]): any {
//logic here
}
datatype
参数是一个与转换函数将返回的接口名称完全对应的字符串(IService1
,IService2
,IService3
等)
为了方便起见,我将函数的返回类型设置为“ any”,但是我想知道是否有一种方法可以使函数返回参数datatype
所指示的特定类型。
我尝试了一些超载,但是服务太多了,我希望Generics
可以解决。我的服务全都是接口,因此任何调用Instance或类似操作的请求都不过分
任何建议将不胜感激
答案 0 :(得分:1)
这应该有效:
function convArrayToObject(datatype: 'type1', fields: string[]): IService1;
function convArrayToObject(datatype: 'type2', fields: string[]): IService2;
function convArrayToObject(datatype: 'type3', fields: string[]): IService3;
function convArrayToObject(datatype: string, fields: string[]): any {
// logic here
}
编辑:另一种解决方案
interface RecordService {
type1: IService1;
type2: IService2;
type3: IService3;
}
function anotherOne<T extends keyof RecordService>(datatype: T, fields: string[]): RecordService[T] {
// logic here
}
const service2 = anotherOne('type2');