首页 > 解决方案 > Typescript - 根据参数返回通用接口类型

问题描述

我有一个将数组转换为各种类型的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) 为了方便起见,我将函数的返回类型设置为“任意”,但我想知道是否有方法使函数返回参数指示的特定类型datatype

我尝试了一些超载,但服务太多,我希望Generics能来救援。我的服务都只是接口,所以任何获取实例或类似的调用都只是过度劳累

任何建议将不胜感激

标签: typescriptgenericstypes

解决方案


这应该有效:

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

推荐阅读