0

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'

1 Answer 1

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

2 Comments

Thanks, I just realized this answers the question as asked - however it infers the class property not the generic directly which is what I'm looking for. The basic example I made allowed a simpler method of extracting the type - but in my real-world case I can't access the type off a property - it's just a generic that get's referenced as return values. Can this answer be updated to reflect getting the generic directly without accessing a property type?
On second thought - this answer is very useful for the way I worded the question - I'll update the title and leave this and ask a new question.

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.