【发布时间】:2018-06-30 13:06:19
【问题描述】:
我尝试定义类型安全的mixin() 装饰器函数,如下所示,
type Constructor<T> = new(...args: any[]) => T;
function mixin<T>(MixIn: Constructor<T>) {
return function decorator<U>(Base: Constructor<U>) : Constructor<T & U> {
Object.getOwnPropertyNames(MixIn.prototype).forEach(name => {
Base.prototype[name] = MixIn.prototype[name];
});
return Base as Constructor<T & U>;
}
}
并按如下方式使用,
class MixInClass {
mixinMethod() {console.log('mixin method is called')}
}
/**
* apply mixin(MixInClass) implicitly (use decorator syntax)
*/
@mixin(MixInClass)
class Base1 {
baseMethod1() { }
}
const m1 = new Base1();
m1.baseMethod1();
m1.mixinMethod(); // error TS2339: Property 'mixinMethod' does not exist on type 'Base1'.
然后,编译器说m1 没有成员'mixinMethod'。
而生成的代码如下,
//...
var Base1 = /** @class */ (function () {
function Base1() {
}
Base1.prototype.baseMethod1 = function () { };
Base1 = __decorate([
mixin(MixInClass)
], Base1);
return Base1;
}());
//...
看起来mixin 装饰器应用正确。
所以,据我了解,m1 的类型被推断为Base1 & MixIn。但是编译器说它只是Base1。
我使用了tsc 2.6.2 并使用--experimentalDecorators 标志编译了这些代码。
为什么编译器无法按我的预期识别类型?
根据@jcalz 的回答,我将代码修改如下,
type Constructor<T> = new(...args: any[]) => T
function mixin<T1, T2>(MixIns: [Constructor<T1>, Constructor<T2>]): Constructor<T1&T2>;
function mixin(MixIns) {
class Class{ };
for (const MixIn of MixIns) {
Object.getOwnPropertyNames(MixIn.prototype).forEach(name => {
Class.prototype[name] = MixIn.prototype[name];
});
}
return Class;
}
class MixInClass1 {
mixinMethod1() {}
}
class MixInClass2 {
mixinMethod2() {}
}
class Base extends mixin([MixInClass1, MixInClass2]) {
baseMethod() { }
}
const x = new Base();
x.baseMethod(); // OK
x.mixinMethod1(); // OK
x.mixinMethod2(); // OK
x.mixinMethod3(); // Property 'mixinMethod3' does not exist on type 'Base' (Expected behavior, Type check works correctly)
这很好用。我想为可变长度混合类改进这个mixin 函数。
一种解决方案是添加如下重载函数声明,
function mixin<T1>(MixIns: [Constructor<T1>]): Constructor<T1>;
function mixin<T1, T2>(MixIns: [Constructor<T1>, Constructor<T2>]): Constructor<T1&T2>;
function mixin<T1, T2, T3>(MixIns: [Constructor<T1>, Constructor<T2>, Constructor<T3>]): Constructor<T1&T2&T3>;
但这太丑了。有什么好主意吗?在支持variadic-kind之前是不可能的吗?
【问题讨论】:
-
+1 用于没有嵌套类的此解决方案的美学。我环顾四周,似乎目前唯一的解决方案就像你说的那样。我想知道是否有某种 ts 预处理器可以动态生成上述重载以使解决方法更容易忍受但无济于事。现在我只是做了一个点头的小工具,它以一种 TS 不会抱怨格式化的方式为 n 重载生成标记。期待合适的解决方案。伟大的工作
标签: typescript generics decorator mixins