【问题标题】:typescript infer generics from properties打字稿从属性推断泛型
【发布时间】:2021-09-29 22:29:14
【问题描述】:

我正在尝试创建一个合并其他两个具有一个或多个泛型的类的类。合并后的类需要从原来的两个类中推断出所有的泛型类型。我尝试使用 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'

【问题讨论】:

    标签: typescript generics type-inference


    【解决方案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;
      }
    }
    

    【讨论】:

    • 谢谢,我刚刚意识到这回答了所问的问题 - 但是它直接推断出类属性而不是我正在寻找的通用属性。我制作的基本示例允许使用更简单的方法来提取类型 - 但在我的实际情况下,我无法从属性访问类型 - 它只是一个泛型,被引用为返回值。是否可以更新此答案以反映在不访问属性类型的情况下直接获取泛型?
    • 再想一想 - 这个答案对我提出问题的方式非常有用 - 我将更新标题并留下这个并提出一个新问题。
    猜你喜欢
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 2021-12-14
    • 2021-03-20
    • 2019-03-12
    • 2022-11-23
    • 2021-07-02
    • 2020-03-22
    相关资源
    最近更新 更多