Create Class Properties using Constructor Assignment

Kamran Ahmed
InstructorKamran Ahmed
Share this video with your friends

Social Share Links

Send Tweet

Instead of manually creating the class properties and assigning them values in the constructor, TypeScript has a better way to let you create and assign values to class properties. All you have to do is prefix the constructor arguments with private or public, TypeScript will automatically create the class properties for the given argument name with the proper access specifier.

Instructor: [0:00] Here we have a class called Person. We're passing it a parameter called name of type String here. Right now, if we try to access the property outside here, let's say, console.log (johndoe.name), Typescript will throw the error because the name is not a part of class Person.

[0:17] If we want to access this outside, we have to define the property here called name type String. We have to do here, this.name = name. The error goes away and we are able to access the name property outside.

[0:30] Typescript has better way to do this property assignment. We can remove the class property from here. We can also remove this assignment from here. All we have to do is assign the access specifier to the property name here. We can do public or private here. The error will go away and we'll be able to access the name property outside.