Initialize properties from generic types in TypeScript

Viewed 105

I have simple code as listed below. I want to autocreate instances of provided generic types and just create multiple services working with different types inside.

All constructors are with parameters.

It is easy in C#, but how to do it in TypeScript?

export class MyClassA {
    constructor(data) {
    }
}

export class MyClassB {
    constructor(data) {
    }
}

export class BaseService<TTypeA, TTypeB> {

    typeA: TTypeA;
    
    typeB: TTypeB;

    constructor(data) {

        // How to create instances of typeA and typeB?
        typeA = new TTypeA(data);
        typeB = new TTypeB(data);
    }
}


export class DataService extends BaseService<MyClassA, MyClassB> {

    constructor(data) {

        super(data)
        
    }
    
    doSomething() {
    
        // Accessing data
        
        // this.typeA ...
        // this.typeB ...
    
    }
}

const data: any = {};
const service = new DataService(data);

I found I need to put some type creator params in constructor to get type in compile time, but how?

0 Answers
Related