【问题标题】:Can't see property of typescript mixins看不到 typescript mixins 的属性
【发布时间】:2021-05-28 07:43:36
【问题描述】:

当我使用 mixins 时,我看不到(与代码/耳语)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'

出了什么问题,我该如何解决?

【问题讨论】:

  • Parent 中的Base 参数的作用是什么?代码从不使用它。
  • 没什么,只是我的测试一团糟

标签: typescript mixins extends


【解决方案1】:

通过将Base 作为参数传递,您将typeof User(构造函数类型)用作TBase,而不是UserUser 实例的类型)。我想你只想要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);

Playground link

其他几点说明:

  • 不需要as any 上的o
  • 旁注:如果您只想要User 的形状而不实现,请使用interface User { id: number; } 而不是class。那么你就不需要@ts-ignore了。 Playground link.

【讨论】:

  • 谢谢@T.J.克劳德!最后一个问题。有什么方法可以在 ParentChild 构造函数中从 TBase 打印(在运行时)对象属性?对于本例中的id: number。我知道类型/接口不是运行时变量。
  • 目标是使用基于泛型类型的默认值创建_object
  • @yihereg819 - 您可以获得属性名称 (Object.getOwnPropertyNames),但不能获得 TypeScript 类型,正如您所说,它们在运行时不存在。 (在这种特殊情况下,typeof o.id 会给你"number",但这仅适用于原语。)如果你想使用来自o 的值而不做你所做的事情(this._object = o),你可以使用Object.assign 做浅拷贝:this._object = Object.assign({}, o); 但我可能没有正确理解你。
猜你喜欢
  • 2022-01-24
  • 2019-07-03
  • 1970-01-01
  • 2020-09-07
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 2019-05-30
相关资源
最近更新 更多