Plastic
Plastic

Reputation: 10318

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:

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.

I tried with some overload but there are too many services and I was hoping that the Generics would come to the rescue. My services are all just Interfaces so any call to get Instance or similar are just overwork

Any suggestion will be appreciated

Upvotes: 1

Views: 958

Answers (1)

HTN
HTN

Reputation: 3594

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

Upvotes: 1

Related Questions