Sandro Rey
Sandro Rey

Reputation: 2979

using generics in TypeScript

I have created this class that works with generics in TypeScript

export class ModelTransformer {

    static hostelTransformer: HostelTransformer;

    static fromAtoB(instance: T): U {
        if (instance instanceof HostelType) {
            return ModelTransformer.hostelTransformer.fromAtoB (instancet);
        }
    }

}

But when I compile it I have those compilation errors:

src/model/transformer/model.transformer.ts:11:47 - error TS2304: Cannot find name 'T'.

11     static fromAtoB(instance: T): U {

src/model/transformer/model.transformer.ts:11:51 - error TS2304: Cannot find name 'U'.

11     static fromAtoB(instance: T): U {

I have tried the solution proposed, but then I have this error:

error TS2366: Function lacks ending return statement and return type does not include 'undefined'.

Upvotes: 0

Views: 111

Answers (1)

user12251171
user12251171

Reputation:

You need to define a "type variable" as described in the handbook, like so:

static fromAtoB<T, U>(instance: T): U {
    if (instance instanceof HostelType) {
        return ModelTransformer.hostelTransformer.fromAtoB (instancet);
    }
}

Upvotes: 1

Related Questions