add a property to a class in typescript

To add a property to a class in TypeScript, you can declare the property in the class definition. For example, let's say you have a class called Person and you want to add a name property to it:

index.ts
class Person {
    name: string;

    constructor(name: string) {
        this.name = name;
    }
}
100 chars
8 lines

In the above example, we declare the name property as a string and initialize it in the constructor. Once the property is declared, you can use it like any other property in the class.

If you want to add a property to an existing class, you can extend the class and add the property in the subclass:

index.ts
class Person {
    constructor(public name: string) {}
}

class Employee extends Person {
    department: string;

    constructor(name: string, department: string) {
        super(name);
        this.department = department;
    }
}
234 chars
13 lines

In the above example, we extend the Person class and add a department property to the Employee class. We initialize the name property in the constructor of the Person class using a shorthand syntax. We also call the super constructor to initialize the name property in the Employee class.

With these examples, you should have a good understanding of how to add properties to classes in TypeScript.

gistlibby LogSnag