简体   繁体   English

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

[英]Typescript - return generic interfaces types depending on parameter

I have a method that turns arrays into javascript objects of various types, the interfaces of these types are similar to these:我有一个方法可以将arrays变成各种类型的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;
    ...
}

And my conversion method is something like:我的转换方法是这样的:

function convArrayToObject(datatype: string, fields: string[]): any {
    //logic here
}

The datatype parameter is a string that corresponds perfectly to the name of the interface that the conversion function will return ( IService1 , IService2 , IService3 etc etc) I set the return type of the function to "any" for convenience but I was wondering if there was a method to make the function return the specific type indicated by the parameter datatype . datatype参数是一个字符串,它与转换 function 将返回的接口的名称完全对应( IService1IService2IService3等)为了方便起见,我将 function 的返回类型设置为“任何”,但我想知道是否有是一种使 function 返回参数datatype指示的特定类型的方法。

I tried with some overload but there are too many services and I was hoping that the Generics would come to the rescue.我尝试了一些超载,但服务太多,我希望Generics能来救援。 My services are all just Interfaces so any call to get Instance or similar are just overwork我的服务都只是接口,所以任何获取实例或类似的调用都只是过度劳累

Any suggestion will be appreciated任何建议将不胜感激

This should work:这应该有效:

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
}

Edit: another solution编辑:另一种解决方案

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM