在TypeScript中基于静态类属性对象的动态字段。

问题描述 投票:0回答:1

我还是一个TypeScript初学者,但现在真的努力在我所有的项目中使用它。所以我面临的问题是这样的。

考虑以下类。

class Parent {
  static attribute = {};
}

class Child extends Parent {
  static attribute = {
    a: true,
  };
}

静态的 attribute 这个类的对象可以是任何类型的对象。[key: string]: any.

重要的细节。我事先不知道里面会有什么。

现在我希望我能做到以下几点。

const child = new Child();
child.a = true;

问题是,如果你还在关注,..: a 不存在于... Child (既不在 Parent 显然!)。) 到目前为止,我唯一能做到这一点的方法是将该字段添加到 Child:

class Child extends Parent {
  static attribute = {
    a: true,
  };

  a!: boolean;
}

所以我的问题是:有没有其他的方法,更多的动态meta来让TypeScript知道。Child 实例可以期待任何来自 attribute? 因此,他们的类型将是 typeof fieldValue.

我知道这是一个很特殊的用例。我只是知道,我不知道如何解决这个用例。

任何帮助将是非常感激的 我希望有一个答案:)

typescript
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.