【发布时间】:2019-12-12 07:49:09
【问题描述】:
我正在将 mixins/traits 与 TypeScript 一起使用,使用子类工厂模式,如 https://mariusschulz.com/blog/mixin-classes-in-typescript 所述。所讨论的特征称为Identifiable,它将id 属性赋予应该表达Identifiable 特征的类。当我尝试以特定顺序将该特征与另一个非泛型特征 (Nameable) 一起使用时,编译失败。
class Empty {}
type ctor<T = Empty> = new(...args: any[]) => T;
function Nameable<T extends ctor = ctor<Empty>>(superclass: T = Empty as T) {
return class extends superclass {
public name?: string;
};
}
function Identifiable<ID, T extends ctor = ctor<Empty>>(superclass: T = Empty as T) {
return class extends superclass {
public id?: ID;
};
}
class Person1 extends Nameable(Identifiable<string>()) { // compiles
constructor(name?: string) {
super();
this.name = name;
this.id = "none";
}
}
class Person2 extends Identifiable<string>(Nameable()) { // fails to compile
constructor(name?: string) {
super();
this.name = name;
this.id = "none";
}
}
编译错误是
src/test/unit/single.ts:30:10 - error TS2339: Property 'name' does not exist on type 'Person2'.
30 this.name = name;
~~~~
无论使用顺序如何,如何正确编译通用特征?
注意:此问题的公共 git 存储库位于 https://github.com/matthewadams/typetrait。如果你想玩这个,请务必查看minimal 分支。
【问题讨论】:
-
@T.J.Crowder 问题现在绝对是最小的。感谢您提供的任何帮助。
-
我没有使用通用特征(看起来很有趣!)。但是很好地减少了这个!现在看起来真的很负责。我 ping 了一个我认识的人。
-
@T.J.Crowder ty -- 希望我能有所收获。这对我来说是一个真正的障碍。 ://
-
@MatthewAdams 感谢减少代码,我也想看它,但因代码太多而无法查看
标签: typescript generics traits mixins typescript-generics