Saving of typing in TypeScript

Hello everybody,

today I want to show two ways of declaring properties in TypeScript.

Take a look at the following TS code:

class Animal {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
}

Here we declared class Animal, with public property name, and we initialized it in construction. But in TS there is another way of shortcutting this way:
class Animal {
    constructor(public  name: string) {
        this.name = name;
    }
}

With TypeScript you can not only pass members for initialization, but also to declare paramethers of constructor as members of class and also configure access modifiers.


No Comments

Add a Comment