打字稿从属性推断泛型

时间:2021-07-22 16:16:50

标签: typescript generics type-inference

我正在尝试创建一个类来合并其他两个具有一个或多个泛型的类。合并后的类需要从原来的两个类中推断出所有的泛型类型。我曾尝试使用 infer 关键字,但我不确定我是否正确使用它,或者它只是没有为我点击。此外,我见过的所有示例都仅推断出一个泛型类型参数,但在我的情况下,我需要从单个类型推断出多个泛型。 TS 游乐场中的示例是我需要的结构,只是缺少对 FooBar 属性的类型推断:

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 个答案:

答案 0 :(得分: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;
  }
}