Extend Functionality of a TypeScript Class with Decorators

Alejandro Roman
InstructorAlejandro Roman
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 years ago

In this lesson, you will learn how to extend a class's functionality through typescript decorators. Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members.

Instructor: [0:00] We would create a function called the class degrader, which will take a generic T. It will take as an argument target which would be of type T. T will extend the new class with args of any type of array and return an object.

[0:23] This function will return a class that extends the target argument, and inside we will create a property called lesson number which will set the T value of one.

[0:43] We will create a class called lesson and inside that class, we'll add a property which is of type number called lesson number, and we will set it to a value zero. We'll instantiate this class by assigning it to a constant called lesson.

[1:06] We will console log this and go to our terminal to observe the zero. Now, using the add syntax we can decorate our class and modify its value. If we now go to our console and log out, we will see one.

[1:29] Similarly, if we change the lesson number in our decorator to two, we will see two. If we change it again to three, we would see three, and we can do four, and five, and so on.

[1:50] As a brief recap, we created a class decorator which took it generic T, and an argument of target which was a type T. That returned a class and extended that argument. We created a class of lesson and decorated it with the decorator to modify its value.

egghead
egghead
~ 11 minutes 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