是否可以仅使用接口而不是类来模拟TypScript的多态this
类型行为?假设我有一些这样的代码:
interface Foo {
foo(): this;
}
interface Bar extends Foo {
bar(): this;
}
function foo(this: Foo) { return this; }
function bar(this: Bar) { return this; }
function newFoo(): Foo {
return { foo };
}
function newBar(): Bar {
return { ...newFoo(), bar }; // Property 'bar' is missing in type 'Foo' but required in type 'Bar'.
}
newBar()
构造函数不进行类型判断,因为来自go struct 化newFoo()
的foo()
的返回类型被推断为Foo
而不是Bar
.
我发现包装mixin的相反方法有效:
function fooish<T>(object: T): T & Foo {
return { ...object, foo };
}
function newBar2(): Bar {
return fooish({ bar }); // Typechecks fine
}
然而,在某些情况下,我更喜欢第一种方法,即有一个简单的构造函数,它只返回Foo
而不是T & Foo
,并通过传播属性而不是应用程序来组合.本质上,我正在寻找的是接口的继承,这样this
仍然正确输入.
有什么 idea 吗?