0

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'.

1
  • 1
    additionally to the Bauke's answer: you need to change the returning type of your method to U | void, for example, since it doesn't return anything in case instance is not instanceof HostelType. Commented Dec 19, 2019 at 8:32

1 Answer 1

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is the correct answer, but because U doesn't have a lower bound and isn't provided as a type argument to fromAtoB, then it's still going to have a type error unless fromAtoB's return type is any, never or another not-lower-bounded type parameter. (Not that Typescript currently supports lower bounds for type variables.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.