【问题标题】:How can I add a property to a class dynamically in typescript?如何在打字稿中动态地将属性添加到类中?
【发布时间】:2017-12-06 12:52:09
【问题描述】:

如何在 typescript 中为类添加属性?

export class UserInfo {
  public name:string;
  public age:number;
}

let u:UserInfo = new UserInfo();
u.name = 'Jim';
u.age = 10;
u.address = 'London'; // Failed to compile. Property 'address' does not exist on type 'UserInfo'.

如何做到这一点?

【问题讨论】:

  • 你想达到什么目的? typescript 的全部目的是拥有定义良好的接口和类,这样你就不会感到意外。为什么 UserInfo 不能包含(可选)address 属性?
  • @k0pernikus 在运行时,我想为其添加其他属性。

标签: typescript


【解决方案1】:

你可以使用索引签名:

export class UserInfo {
    [index: string]: any;
    public name: string;
    public age: number;
}

const u: UserInfo = new UserInfo();
u.name = "Jim";
u.age = 10;
u.address = "London";

console.log(u);

将输出:

$ node src/test.js
UserInfo { name: 'Jim', age: 10, address: 'London' }

但请注意,您因此失去了严格的类型检查并引入了在弱类型语言中容易发生的潜在错误。

【讨论】:

    猜你喜欢
    • 2019-12-24
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多