Create Class Properties using Constructor Assignment

Kamran Ahmed
InstructorKamran Ahmed
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

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.

egghead
egghead
~ 2 hours ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today