简体   繁体   中英

Typescript generic type inference based on inheritance

Consider this code:

class A<T> { t?: T; }
interface B {}
class C implements A<B> {}
function f<T1 extends A<T2>, T2>(a: T1): T2 | undefined { return a.t; }

const result = f(new C());
const result2 = f(new A<B>());

It turns out that the type of result or even result2 will be unknown , while it can be inferred from the context, as C is implementing A<B> (so it can be inferred as B ).

Why typescript does not do that? Is it a missing feature, a non-sound inference or is there another way to achieve desired behavior?

I could find my own answer, and I have to say TypeScript is flawless!

class A<T> { t?: T; }
interface B {}
class C extends A<B> {}

type ExtractGeneric<T> = T extends A<infer X> ? X : never;
function f<T1 extends A<T2>, T2 = ExtractGeneric<T1>>(a: T1): T2 | undefined { return a.t; }

const result = f(new C());
const result2 = f(new A<B>());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM