我遵循了这些docs并设置了一个mixin类:
class ClassA {
firstName(): string {
return "James";
}
}
class ClassB {
lastName(): string {
return "Bond";
}
}
class Mixin {} // <--
interface Mixin extends ClassA, ClassB {}
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name));
});
});
}
applyMixins(Mixin, [ClassA, ClassB])
for (const name of Object.getOwnPropertyNames(ClassA.prototype)) {
const method = ClassA.prototype[name];
if (typeof method === "function") {
Mixin.prototype[name] = ClassA.prototype[name];
}
}
for (const name of Object.getOwnPropertyNames(ClassB.prototype)) {
const method = ClassB.prototype[name];
if (typeof method === "function") {
Mixin.prototype[name] = ClassB.prototype[name];
}
}
const mixin = new Mixin();
console.log("Mixin contains: " + mixin.firstName() + " and " + mixin.lastName());
const asClassA = mixin as ClassA;
console.log(asClassA);
const asClassB = mixin as ClassB;
console.log(asClassB);
const isIstanceOfA = (mixin instanceof ClassA);
console.log(isIstanceOfA);
const isIstanceOfB = (mixin instanceof ClassB);
console.log(isIstanceOfB);
使用mixinclass时,无法正确将其强制转换为ClassA
/ ClassB
。并且使用instanceOf
-我得到了假。
mixin类丢失了原始类型吗?还是我错过了什么?
它打印:
Mixin包含:James和Bond
ClassB {}
ClassB {}
false
false
到控制台。
我找到了另一个typescript doc example。还有另一个示例here。 Here。但是用ts-node运行它们,我得到:
ReferenceError:__extends未定义
function Tagged<T extends Constructor<{}>>(Base: T) {
return class extends Base { // <-- error thrown here
_tag: string;
constructor(...args: any[]) {
super(...args);
this._tag = "";
}
}
}
虽然可以运行它NativeScript,但是我最初打算使用它。