DEV Community

Seyram Ofori
Seyram Ofori

Posted on

TIL; typescript - classes | public fields in constructor

  • the use of public on arguments on the constructor is a shorthand that allows us to automatically create properties with that name
class Student {
    fullName: String;

    constructor(
        public firstName: string,
        public lastName: string
    ){
        this.fullName = firstName + " " + lastName;
    }

}
Enter fullscreen mode Exit fullscreen mode

in this case, the class has been given 3 public properties; fullName, firstName and lastName. firstName and lastName were created as public properties on the class by using the public keyword in the constructor params

  • classes in TS are just a shorthand for the same prototype-based OO that is frequently used in JS

Top comments (0)