mercredi 19 décembre 2018

Typescript Generic as Parameter

I have a class:

export class BaseClass<T> {
    constructor(data?: Partial<T>) {
        Object.assign(this, data);
    }
    name: string;
    id: number;
}

From this class, I extend the properties:

export class ExampleOne extends BaseClass<ExampleOne> {
    isReusable: boolean;
}

export class ExampleTwo extends BaseClass<ExampleTwo> {
    propOne: string;
    propTwo: boolean;

}

I've used a mapped type in BaseClass so that I could have "similar" syntax to that of C# to initialize an object as well as reuse the constructor in subsequent, classes that inherit BaseClass.

var x = new ExampleTwo({name: 'test', id: 1, propOne: 'test', propTwo: false});

This all seems to be working fine, but I would like to pass any one of these derived classes as a parameter to another function.

testFunction(data: BaseClass<T>) {
    //logic
}

I receive an error stating that the build Cannot find name T. I changed the signature to

testFunction(data: BaseClass<any>) {
    //logic
}

and that appeared to work, but I feel like there should be a better way to handle this.

What am I missing?





Aucun commentaire:

Enregistrer un commentaire