Classes
Video Lecture
Section | Video Links |
---|---|
Classes |
Overview
Every design pattern in the course uses classes, so it is appropriate to get a basic understanding of them.
Simply, they are a template that can be used when creating custom objects.
Class Example 1
Update ./src/test.ts
with this script
1 2 3 4 5 6 7 8 9 10 |
|
Re compile and execute,
tsc -p ./src
node ./dist/test.js
Outputs
Cat is walking
If you inspect the compiled javaScript in ./dist/test.js
you will see that it is also very similar to the ./src/test.ts
.
1 2 3 4 5 6 7 8 9 |
|
Classes are a JavaScript concept, but TypeScript allows us to add type safety to them.
Note
Note that in the above "Re compile and execute" commands I have written them as two steps. You may prefer to keep tsc
running in watch mode as described in the TSC Watch section so that you don't need to keep running tsc -p ./src
for every new edit.
Class Example 2
Below is a more complicated class including more specific functionality.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Re compile and execute,
tsc -p ./src
node ./dist/test.js
Outputs
Cosmo the cat, has walked 20 steps.
If you inspect the compiled javascript in ./dist/test.js
once again, you will see that it is also very similar to the TypeScript source except that the main difference is that all of the type annotations have once again been removed.
Looking at the second example more closely, I added a local property called name
. This is required to be a string. When the Cat is instantiated using the new
keyword, I am also passing in a string to be used as the name. The constructor
will assign the name
that was passed in, to the classes property also called name
, but it refers to that internal class property as this.name
.
Further down in the walk method
, I also use this.name
in the outputted string, plus another attribute value steps
which was passed into the walk
method. Note steps
isn't referred to as this.steps
since steps
is declared in the method scope, and not the class scope.
Class Example 3
In this third example I will expand on the return types of the class methods.
Replace ./src/test.ts
with this script below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
Re compile and execute,
tsc -p ./src
node ./dist/test.js
Outputs
Cosmo the cat, has walked 20 steps.
Cosmo the cat, has walked 20 steps.
Cosmo the cat, has walked a total of 40 steps.
You will notice that the walk
method now increments a value used to keep track of the total steps walked, and the totalStepCount()
method returns a value of type number
.
Also note that I've initialized stepsWalked
with the value 0
, rather than setting it to 0
in the constructor. This is your choice. In strict
mode, you can either initialize any variables as they are declared in the class, or within the classes constructor.