【发布时间】: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