Friday, April 16, 2021

Typescript: Shorthand Initialization

In a lot of use cases, the fields are initialized in the constructor.

class Person {

    // Fields declaration 
    name : string;
    private id : string;

    // Initial the field value in constructor
    constructor(name : stringid : string) { 
        this.name = name;
        this.id = id;
    }

}

You can simplify to

class Person {

    constructor(private name : stringpublic id : string) {}

}

No comments:

Post a Comment