【发布时间】:2021-03-20 17:56:24
【问题描述】:
loggerOfHidden 函数的 ctx 参数应该有什么签名才能工作?
'T' could be instantiated with an arbitrary type which could be unrelated to '(Anonymous class)' 错误是什么意思?
忽略它输出的错误就好了。
Argument of type 'this' is not assignable to parameter of type 'T & Constructor<ISayHidden>'.
Type '(Anonymous class)' is not assignable to type 'T & Constructor<ISayHidden>'.
Type '(Anonymous class)' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to '(Anonymous class)'.
Type 'this' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to 'this'.
Type '(Anonymous class)' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to '(Anonymous class)'
type Constructor<T> = new (...args: any[]) => T;
interface ISayHidden {
sayHidden(): void;
}
class Factory<T extends Constructor<Foo>> {
constructor(public Base: T) {}
ExtendSayHidden(loggerOfHidden: (ctx: T & Constructor<ISayHidden>) => void) {
return new Factory<T & Constructor<ISayHidden>>(class extends this.Base implements ISayHidden {
sayHidden() {
loggerOfHidden(this);
}
});
}
}
class Foo {
hiddenMessage = 'Wow, you found me!';
sayHi() {
console.log('Hi!');
}
sayBye() {
console.log('Bye!');
}
}
const FooExtended = new Factory(Foo).ExtendSayHidden(ctx => {
console.log(ctx.hiddenMessage);
}).Base;
let fooExtended = new FooExtended();
fooExtended.sayHidden();
编辑:loggerOfHidden 的未来用途将是操作由ExtendSayHidden 函数生成的扩展实例。请注意,Factory 可以并且将包含大量函数,每个函数都将进一步扩展当前的 Base 类。我只是想让 TypeScript 假装 ctx 不超过 Foo 由当前类扩展,并且能够访问这些字段。如果需要,我可以创建一个更广泛的示例。
EDIT2:更新示例。 TypeScript 可以为ctx 提供当前类的上下文吗?
type Constructor<T> = new (...args: any[]) => T;
interface ISayHidden {
hiddenMessage: string;
sayHidden(): void;
}
class Factory<T extends Constructor<Foo>> {
constructor(public Base: T) {}
ExtendSayHidden(loggerOfHidden: <U extends Foo>(ctx: U) => void) {
return new Factory<T & Constructor<ISayHidden>>(class extends this.Base implements ISayHidden {
hiddenMessage = 'Wow, you found me!';
sayHidden() {
loggerOfHidden(this);
}
});
}
}
class Foo {
sayHi() {
console.log('Hi!');
}
sayBye() {
console.log('Bye!');
}
}
const FooExtended = new Factory(Foo)
.ExtendSayHidden(ctx => {
console.log(ctx.hiddenMessage);
}).Base;
let fooExtended = new FooExtended();
fooExtended.sayHidden();
【问题讨论】:
-
您能否提供一个上下文,这些函数应该做什么?
标签: typescript mixins typescript-generics