Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infer TypeScript generic class type

B extends a generic class A. I need to be able to infer the generic type of the extended A of B. See code below.

I used this in previous Typescript versions successfully but for my current project using 3.2.4 (also tried latest 3.4.5) the inferred type seems to result in {} instead of string.

Any idea what I'm doing wrong? This can't possibly have changed?

class A<T> {

}

class B extends A<string> {

}

type GenericOf<T> = T extends A<infer X> ? X : never;

type t = GenericOf<B>; // results in {}, expected string
like image 649
Fabio Scala Avatar asked May 31 '26 13:05

Fabio Scala


1 Answers

Currently a class who has a generic that isn't used in the class literally has the same "structure" as {} hence the inference. The change that was made that broke your functionality was a bug fix and the workaround is to use "A's" generic somewhere inside the class and the inference will work again.

Hope this helps.

class A<T> {
    hello: T = "" as any; // note that i have used the generic somewhere in the class body.
}
class B extends A<string> {}
type GenericOf<T> = T extends A<infer X> ? X : never;
type t = GenericOf<B>; // string.
like image 149
Shanon Jackson Avatar answered Jun 02 '26 08:06

Shanon Jackson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!