Typescript-根据参数返回通用接口类型

时间:2019-11-14 10:25:35

标签: typescript generics types

我有一种将数组转换成各种类型的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参数是一个与转换函数将返回的接口名称完全对应的字符串(IService1IService2IService3等) 为了方便起见,我将函数的返回类型设置为“ any”,但是我想知道是否有一种方法可以使函数返回参数datatype所指示的特定类型。

我尝试了一些超载,但是服务太多了,我希望Generics可以解决。我的服务全都是接口,因此任何调用Instance或类似操作的请求都不过分

任何建议将不胜感激

1 个答案:

答案 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');