2017-07-03 40 views
0

如何將屬性添加到打字稿中的類中?如何在打字稿中動態地將屬性添加到類中?

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

你想達到什麼目的?打字稿的全部用途是具有定義良好的界面和類,以便您不會感到驚訝。爲什麼UserInfo不能包含(可選)'address'屬性? – k0pernikus

+1

可能的重複[如何動態地將屬性分配給TypeScript中的對象?](https://stackoverflow.com/questions/12710905/how-do-i-dynamically-assign-properties-to-an-object-in -typescript) – k0pernikus

+0

@ k0pernikus在運行時,我想爲它添加其他屬性。 – niaomingjian

回答

0

你可以使用索引簽名:

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' } 

但是注意,從而你正在失去嚴格typechecks並引入潛在的錯誤是一個容易出現在弱類型語言。

相關問題