Reputation: 1060
I'm trying to create a class that merges two other classes that have one or more generics. The merged class needs to infer all of the generic types from the original two classes. I've attempted to use the infer keyword but I'm not sure I'm using it correctly or it just hasn't clicked for me. Also, all the examples I've seen only infer a single generic type parameter, but in my case, I need to infer multiple generics from a single type. Example in TS playground that is the structure I need, just missing the type inference to the FooBar properties:
class Foo<A, B> {
constructor(public a: A, public b: B) {}
}
class Bar<C> {
constructor(public c: C) {}
}
class FooBar <F extends Foo<any, any>, B extends Bar<any>> {
// How do I infer these properties?
a: any;
b: any;
c: any;
constructor(foo: F, bar: B) {
this.a = foo.a;
this.b = foo.b;
this.c = bar.c;
}
}
const foo = new Foo(1, 'two');
foo.a // ts knows this is 'number'
foo.b // ts knows this is 'string'
const bar = new Bar(true);
bar.c // ts knows this is 'boolean'
const foobar = new FooBar(foo, bar);
foobar.a // this type is now 'any'
foobar.b // this type is now 'any'
foobar.c // this type is now 'any'
Upvotes: 0
Views: 546
Reputation: 616
class FooBar <F extends Foo<any, any>, B extends Bar<any>> {
a: F['a'];
b: F['b'];
c: B['c'];
constructor(foo: F, bar: B) {
this.a = foo.a;
this.b = foo.b;
this.c = bar.c;
}
}
Upvotes: 1