问题描述
当我使用 mixins 时,我看不到(vs 代码/耳语)id
我的财产。
我的代码是:
class User {
// @ts-ignore
id: number;
}
function Parent<TBase>(Base: TBase) {
return class ParentChild {
_object: TBase;
constructor (o: TBase) {
this._object = o;
}
dump(): void {
console.log(this._object);
}
};
}
class Test extends Parent(User) {
}
const o = {id: 2} as any;
const i = new Test(o);
// problem
console.log(i._object.id);
问题出在 console.log(i._object.id);
行上。我收到一个错误:Property 'id' does not exist on type 'typeof User'
。
出了什么问题,我该如何解决?
解决方法
通过传递 Base
作为参数,您将 typeof User
(构造函数类型)用作 TBase
而不是 User
({{1} } 实例)。我认为您只需要 User
,通过指定通用参数:
User
其他一些注意事项:
-
class User { // @ts-ignore id: number; } function Parent<TBase>() { // ^^^^^^^^^ return class ParentChild { _object: TBase; constructor (o: TBase) { this._object = o; } dump(): void { console.log(this._object); } }; } class Test extends Parent<User>() { // ^^^^^^^^^^^^^^ } const o = {id: 2} as any; const i = new Test(o); // problem console.log(i._object.id);
上不需要as any
。 - 旁注:如果您只想要
o
的形状而不需要实现,请使用User
而不是interface User { id: number; }
。那么您将不需要class
。 Playground link。