如何在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'.
如何实现这一目标?
答案 0 :(得分: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' }
然而请注意,因此您正在放弃严格的类型检查并引入在弱类型语言中容易发生的潜在错误。