Check out a free preview of the full TypeScript 5+ Fundamentals, v4 course
The "Class Fields & Methods" Lesson is part of the full, TypeScript 5+ Fundamentals, v4 course featured in this preview video. Here's what you'd learn in this lesson:
Mike explains how classes are used in JavaScript and how TypeScript adds additional features and syntax to define class fields, methods, and static fields. A demonstration of the use of static blocks, a recent addition to TypeScript and JavaScript, for class-level setup is also provided in this segment.
Transcript from the "Class Fields & Methods" Lesson
[00:00:00]
>> The next topic we're going to talk about is classes, so hopefully you are familiar with classes as they exist in JavaScript. So you're familiar with the constructor function. This is what's called when you invoke a constructor and you'd say new car. We're building on our example of a car here by giving this class a make model and year.
[00:00:28]
So in regular JavaScript, you might not see these. And you would be able to kind of set these dynamically, you can just sort of dropped properties on an instance. Because one of the goals of TypeScript is to, Any value that you're passing around, you have to define in some way, class fields upfront.
[00:00:57]
And so this looks a little bit verbose. But you can see there's carved out model. And then this is the model that comes in from the constructor. It looks for both, I promise we're gonna get to something a little bit later called puram properties, which reduce some of the syntax down significantly.
[00:01:15]
Here effectively we're seeing make model and year three times. In the parameters for the constructor and then in the names of the class fields actually it's four times and then twice in each of these lines here will trim that down. So you see those words once each and in a much more abbreviated syntax.
[00:01:39]
So If we were using regular JavaScript like we wouldn't get any help necessarily on whether we're invoking the right methods on a class like there is no activate turn signal here. Here we're passing in arguments in the wrong order. So just like with a function type a construct signature will validate that you're passing in that year as the last, the third parameter here.
[00:02:05]
So this is TypeScript doing its job right at the gate just by using class fields. So, let's talk a little bit about methods. Methods are something that lives on a class. So I'm gonna grab this hunk method and I'm gonna just drop it right into the class. And here we're emitting a string where the number of O's in the honk is determined by the argument you pass in.
[00:02:32]
And here you can see we're able to create a new car. And c.honk, take my word for it, it would return this particular string. But this is a method now. This looks a lot like typing a function, like the freestanding functions that we've been working with. Right, the arguments are the same.
[00:02:52]
Optional fields are the same if you wanted to do this. Right, methods are pretty easy, or pretty much natural extension from typing functions. So there's something new that has arrived in JavaScript recently, which for me means like the last several years, static fields. [COUGH] So I'm gonna grab this, just another chunk of stuff we're gonna add to car I'm gonna put it up here.
[00:03:23]
I'm just gonna sort these in the way I would sort it if I were doing this for real. Cool, so what just happened? Well, we have a static field called the nextSerialNumber. And when we say it's a static field, let me just get these out of the way so I can squeeze something down here.
[00:03:48]
Look at that I can call nextSerialNumber on the car class itself, not an instance of the class, the car class itself. So this is what we mean by the static side of a class. It's where the constructor lives. Not instance properties, this is a class field. And similarly, this is a class method.
[00:04:11]
Generate next serial number, we could call that and it would invoke nextSerialNumber++. We just spent a lot of time talking about this and In a class method, what we're looking at here, this Is of type of car. Not to be confused with down here This is not being very useful to me, it's car in an instance.
[00:04:51]
Car being the interface describing a car, right? See, there it is, car, Up here. Type of car. Type of car represents the static side of the class. Thats it's as if we're in there doing the following. Not new car, but just car. They're sort of just like things dangling off of the class itself.
[00:05:24]
So that's what this is in a static field context. Okay, we have a we have a missing member field here, which I can go ahead and add real quick. So we'll just say serial number. And we'll say car dot generate serial number. So, this this we would say is a class field.
[00:05:52]
And this is a class field initializer. So you can think of it as we're processing this class. And we go down and we find that field and we invoke, generate serial number and assign whatever the return value is to serial number. You sure could go down here and say this.serialNumber = car.generateSerialNumber.
[00:06:18]
In fact, it's equivalent to that. Generally ordering doesn't matter. We'll look a little bit at ordering later. Like, when is this run? When are these things run? One has to be first and we'll see later. But the main goal for me when I'm using field initializers like this.
[00:06:40]
Is I want stuff out of the constructor. It's really nice to be able to look at this one line and say, okay, there's this thing. It's a serial number, it starts out with a value that comes from here. And, of course, because this returns a number, we don't need an explicit type here.
[00:06:55]
Here we do because you kind of need to know what those fields are before we start dealing with this code. We need to know up front what they will be. All right, and here because we have added, I think I got my example code here a little wrong.
[00:07:15]
No, I have it right. So the thing that's been added to get label is a little hash tag with the serial number. And here we go. I'm just indicating that it's going to increment by one, because we have that static field where we're holding the next serial number and it keeps incrementing over and over.
[00:07:30]
There's another static thing we can do called a static block. This is a very recent addition to Typescript and to JavaScript, and here's what that looks like a static block. So let's imagine that instead of just saying I'm gonna set my serial number equal to 100 what I wanna do is make an API call to some endpoint that gets me some serial number data.
[00:08:01]
And I wanna say the starting serial number is whatever the API says. Like it'll tell me where I last left off. And I'll start counting from there. So we would delete this for sure. And this code ends up initializing that field. Now, when is this code run? It's run very shortly after the car class declaration is processed.
[00:08:36]
What that means is, you don't have to create an instance in order for this to run. This is run before you create any instances. I mean, it's async here. So I'll say, the fetch is dispatched before any instances are created. This needs some sort of readiness indicator where you would say don't create any cars until we have the serial numbers that we start with.
[00:08:58]
But conceptually, this is sort of like class level setup stuff similar to the way this is set up stuff for an instance. This could be set up stuff for the class itself, a static block. This is not something that you invoke specifically, it's just something that runs immediately after, this class declaration here is kind of evaluated, and you eval this file and the static block will run.
[00:09:34]
And I think you can have more than one. You can have more than one. So you could have a couple, they're gonna run from top to bottom, and you could comment on each of them to say what's the purpose of this thing? A very special thing, but it's something that you could see with the static keyword and it can live on a class as of very recent Javascript and Typescript versions.
Learn Straight from the Experts Who Shape the Modern Web
- In-depth Courses
- Industry Leading Experts
- Learning Paths
- Live Interactive Workshops