Check out a free preview of the full TypeScript Fundamentals course:
The "Mixins & Classes" Lesson is part of the full, TypeScript Fundamentals course featured in this preview video. Here's what you'd learn in this lesson:

After showing mixins patterns, which are abstract classes, Mike reviews how to define the shape of classes in TypeScript.

Get Unlimited Access Now

Transcript from the "Mixins & Classes" Lesson

>> Mike: Mixins, which can be thought of as abstract classes, this is a pattern for potentially decorating classes with additional behavior. And this can lead to complexity, which can lead to trouble, but I just wanted to point out that this pattern exists, mixins exist. And what we have here is a function called AsJSON.

[00:00:27] It takes it as an argument something, and what it returns is a subclass of that something, right? So we basically, we pass in a type. And what we get is a new type that extends from whatever we passed in, but this has an AsJSON method, right? And so, then down below, we can use this mixin by basically saying, this person extends the regular object type.

[00:00:53] Decorated by this AsJSON thing, right, which, of course, means we're really getting class extends object, right? We're getting a sub-class of object. So I just want you to know that class, like class expressions and functions can be mixed together to create something like this. So just be careful with this kind of thing.

[00:01:18] Because you do have to be aware of any potential collisions between different things that are extended on top of other classes.
>> Mike: Okay, so now we are back in the TypeScript mode, so we are looping back. One thing that we are going to see is obvious here. And I already kind of showed you this inadvertently as I was hacking around with the static stuff.

[00:01:48] We need to define the shape of this upfront, the shape of this object upfront. So classes, just like interfaces, need to have a very explicitly defined shape. So it starts to look a little bit repetitive but looking at this, we can see, okay, car has a make, model, and a year.

[00:02:07] And then we take these three arguments in our constructor and we type them. And then we assign those to our member data inside the constructor and then we can get a car that looks like this. So just make sure that you, in particular, type, you can let your editor give you appropriate feedback.

[00:02:27] But you'll find in most cases, you have to type arguments that are passed in and member function in the class. Just because, you have to know what can be passed into the constructor. And then ensure that those are values that can be assigned to the member data. Just follow the guidance of the language service and you will get the hang of it.

>> Mike: But then we can create a new car like this.