0

I have a generic class Generic<T> and another generic class having another generic class as a generic type which is GenericWrap<U extends Generic<any>. It has a Generic<any> as a member. (Please see the code below)

Now NumberGenericWrap extends GenericWrap with a generic type <NumberGeneric>. At this point, I want the type of NumerGenericWrap.generic to be Generic<number> so the return type of NumberGenericWrap.getValue() can be number. But it ends up with any type.

Does typescript support this?

class Generic<T> {
    val: T;
}

class NumberGeneric extends Generic<number> {

}

class GenericWrap<U extends Generic<any>> {

    generic: U;

    getValue() {
        return this.generic.val;
    }
}

class NumberGenericWrap extends GenericWrap<NumberGeneric> {

}

let n = new NumberGenericWrap();

// expected 'typeof val' => number 
// actual 'typeof val' => any
let val = n.getValue();
2
  • Why aren't all of the those typed in T, so GenericWrap contains generic: Generic<T> and class NumberGenericWrap extends GenericWrap<number>? Commented Apr 13, 2019 at 7:12
  • @jonrsharpe actually, what you said is what my code is just doing now and it actually works well. But it leaves some ambiguity for my case. Thinking in design perspective, number is a first-level data, NumberGeneric is a second-level and finally GenericWrapis the third level which is the highest level. So having second-level data as a generic type for third-level data makes sense rather than first-level one. Commented Apr 14, 2019 at 5:43

1 Answer 1

1

I don't know exactly why is type checker not trying to infer val type, but it has workaround though. Just tell type checker to do the lookup to that generic type and find val type.

type ValType<T extends Generic<any>> = T["val"];

class GenericWrap<U extends Generic<any>> {

    generic: U;

    getValue(): ValType<U> {
        return this.generic.val;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.