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'.
如何才能做到這一點?
你想達到什麼目的?打字稿的全部用途是具有定義良好的界面和類,以便您不會感到驚訝。爲什麼UserInfo不能包含(可選)'address'屬性? – k0pernikus
可能的重複[如何動態地將屬性分配給TypeScript中的對象?](https://stackoverflow.com/questions/12710905/how-do-i-dynamically-assign-properties-to-an-object-in -typescript) – k0pernikus
@ k0pernikus在運行時,我想爲它添加其他屬性。 – niaomingjian