2

How can I add a property to a class in 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'.

How to achieve this?

niaomingjian
  • 3,472
  • 8
  • 43
  • 78
  • What are you trying to achieve? The whole purpose of typescript is to have well-defined interfaces and classes so that you don't have surprises. Why can't UserInfo contain an (optional) `address` property? – k0pernikus Jul 03 '17 at 09:49
  • 1
    Possible duplicate of [How do I dynamically assign properties to an object in TypeScript?](https://stackoverflow.com/questions/12710905/how-do-i-dynamically-assign-properties-to-an-object-in-typescript) – k0pernikus Jul 03 '17 at 09:54
  • @k0pernikus At running, I'd like to add other properties for it. – niaomingjian Jul 03 '17 at 09:56

1 Answers1

5

You could use index signature:

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);

Will output:

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

Yet note that thereby you are loosing the strict typechecks and introduce potential bugs that a prone to happen in weakly typed languages.

k0pernikus
  • 60,309
  • 67
  • 216
  • 347
  • I have a generic type Facade> and want to access the members like in simple record: Facade.Member.method() - is it possible in typescript? – Crusader Nov 09 '22 at 16:31