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?

3
  • 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? Commented Jul 3, 2017 at 9:49
  • 2
    Possible duplicate of How do I dynamically assign properties to an object in TypeScript? Commented Jul 3, 2017 at 9:54
  • @k0pernikus At running, I'd like to add other properties for it. Commented Jul 3, 2017 at 9:56

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I have a generic type Facade<T extends Record<string, AbstractClass>> and want to access the members like in simple record: Facade.Member.method() - is it possible in typescript?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.