The class keyword introduced in ES2015 is also supported in TypeScript. Just like other JavaScript features, TypeScript adds type strictness in classes as well. Let’s start by creating a TypeScript workspace in your IDE of choice.
In an empty folder create a file called index.ts and a file called tsconfig.json. In the second file paste the following code. Also, make sure TypeScript is installed on your system.
1 2 3 4 5 6
{ "compilerOptions": { "target": "esnext", "watch": true } }
Here, the watch: true key-value pair will automatically compile the code anytime we hit save into a file called index.js, which we can then run.
Now that your TypeScript workplace is set up let’s declare a class. The class declaration begins with the keyword “class” and then we write the name of the class, then curly braces. Inside the curly braces we define our class. For example,
1 2 3 4
class Point { x: number; y: number; }
Here, we have declared a class called Point which represents a point in mathematical 2-d space and has two fields “x and y”. These fields are public in nature which means the functions that are not a part of this class can also access these variables. Add the following code in the index.ts file.
1
2
3
4
const pt = new Point();
pt.x = 2;
pt.y = 3;
console.log(`{pt.x}, {pt.y}`)
On saving and then running the JavaScript file we get to see this x and y.
Constructors are functions that are executed as soon as you create an object of a class and are used to initialize the object’s field values. For example, modify the code in index.ts like this.
1
2
3
4
5
6
7
8
9
10
11
class Point {
x: number;
y: number;
constructor() {
this.x = 0;
this.y = 0;
}
}
const pt = new Point();
console.log(`{pt.x}, {pt.y}`)
The output will be:
This means our constructor works fine. Sometimes you may want the users to not declare fields without assigning a default value. To do that you can modify the tsconfig.json file like this.
1 2 3 4 5 6 7 8
{ "compilerOptions": { "target": "esnext", "watch": true, "strictNullChecks": true, "strictPropertyInitialization": true } }
The property strictPropertyInitialization needs you to initialize fields. Now if we remove the constructor we will get the following error.
If you want, a few fields should be allowed to go without initialization because they might be getting filled by external libraries. Then you can do this for that field.
y!: number;
Note that initialization should always be done in a constructor.
You can also make your fields read only, which will make those fields read only outside of constructors.
For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
class Student {
name: String;
readonly rollNum: String;
constructor(name, rollNum) {
this.name = name;
this.rollNum = rollNum;
}
}
const s1 = new Student("Srajan", "A3");
console.log(`{s1.name}, {s1.rollNum}`);
s1.rollNum = "A2";
console.log(`{s1.name}, {s1.rollNum}`);
The rollNum is a field that cannot be modified outside the constructor, so the second last line should give us an error.
Let’s remove the last two lines and run the code now.
Our code runs fine now.
If your class is derived from some other class then you have to call super() before using “this” keyword. The good thing about TypeScript is that unlike JavaScript it tells us whenever super() is needed. For example, type the following code in your TypeScript file.
1
2
3
4
5
6
7
8
9
10
11
12
13
class Person {
name: String;
constructor(name) {
this.name = name;
}
}
class Student extends Person {
readonly rollNum: String;
constructor(rollNum) {
this.rollNum = rollNum;
}
}
You get the following error:
Constructors for derived classes must contain a 'super' call.ts(2377)
Now, modify your code like this and it will work just fine.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Person {
name: String;
constructor(name) {
this.name = name;
}
}
class Student extends Person {
readonly rollNum: String;
constructor(name, rollNum) {
super(name);
this.rollNum = rollNum;
}
}
const s1 = new Student("Srajan", "A3");
console.log(s1.name, s1.rollNum);
Methods are functions inside of a class. For example,
1
2
3
4
5
6
7
8
9
10
11
12
class Person {
name: String;
constructor(name) {
this.name = name;
}
greeting(greeting: string): string {
return greeting + " " + this.name;
}
}
const p = new Person("Srajan");
console.log(p.greeting("Hello"));
Here the greeting argument is of type string and the return type of function is also of type string.
This was the basics for TypeScript classes.