- Published on
Day24 : Learning TypeScript: Using Class in TypeScript
- Authors

- Name
- irisjustdoit
- @irisjustdoit
Day24 : Learning TypeScript: Using Class in TypeScript
Today we will learn about using Class in TypeScript. Class Members include: Fields, Readonly, Constructors, Methods, Getters/Setters, and Index Signatures.
Fields & Readonly
- Instance properties: In ES6, properties cannot be directly defined in the class; they must be defined in the constructor using
this. In ES7, properties can be directly defined in the class, and TypeScript follows suit, allowing properties to be defined directly in the class, and they are public by default. readonly: You can use thereadonlykeyword to create read-only properties, preventing assignment.
class Point {
x: number; // Instance property
y: number;
readonly name: string = "show point"; // Readonly property
constructor(x = 0, y = 0) { // Default to 0
this.x = x;
this.y = y;
}
printPoint() {
console.log(`x: ${this.x}, y: ${this.y}`);
}
}
let p = new Point(2, 4);
p.printPoint(); // x: 2, y: 4
p.name = "hihi"; // Error: Cannot assign to 'name' because it is a read-only property.
--strictPropertyInitialization(tsconfig.json): Checks for property assignment in class instances. In the example below, thenameproperty type is declared but not assigned, resulting in an error.
class GoodGreeter {
name: string; // Error: Property 'name' has no initializer and is not definitely assigned in the constructor.
word: string;
constructor() {
this.word = "hello";
}
}
Constructors
Constructors are similar to functions; you can use type annotations and default parameters. However, the official documentation mentions overloads, which raises a question: JavaScript classes only have one constructor, so can TypeScript have multiple?
class Point2 {
x: number;
y: number;
// Normal signature with defaults
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
}
let p2 = new Point2(100, 200);
class Point {
// Overloads
constructor(x: number, y: string);
constructor(s: string);
constructor(xs: any, y?: any) {
// TBD
}
}
Later, I found out that multiple constructors are not allowed; you cannot overload constructors. I think they meant that methods can be overloaded, providing multiple type definitions for a single function.
class Point3 {
x: number;
y: string;
constructor(x: number, y: string) {
this.x = x;
this.y = y;
}
}
let p3 = new Point3(1, "5");
let p4 = new Point3("hello");
console.log(p3); // Point3 { x: 1, y: '5' }
console.log(p4); // Point3 { x: 'hello', y: undefined }

Super Call
In JavaScript, we sometimes forget to use super before this to call the parent class, but in TypeScript, if we forget to use super, the compiler will remind us.
class Base {
k = 4;
}
class Derived extends Base {
constructor() {
console.log(this.k);
// 'super' must be called before accessing 'this' in the constructor of a derived class.
super();
}
}
Methods
This is the same as in JavaScript; you can add methods to the class and define parameter types. Additionally, to use class properties within methods, you need to use the this keyword.
let z: number = 0;
class Point4 {
x = 10;
y = 10;
z: string = "hello";
// Method
scale(n: number): void {
this.x *= n;
this.y *= n;
}
// Modify the class's z property; use this.z, otherwise it will modify the external z
editZ() {
z = "world"; // Error: Type 'string' is not assignable to type 'number'.
}
}
Getters / Setters
Classes also have accessors, which are getters and setters, used to change how properties are read and assigned, similar to ES6 classes. Additionally, TypeScript 4.3 introduced a new feature where the parameter types for set can be multiple types.
class Thing {
_size = 0;
get size(): number {
return this._size;
}
set size(value: string | number | boolean) {
let num = Number(value);
// Don't allow NaN, Infinity, etc
if (!Number.isFinite(num)) {
this._size = 0;
return;
}
this._size = num;
}
}
let thing = new Thing();
console.log(thing.size); // 0
thing.size = "seven";
console.log(thing.size); // 0
thing.size = 2.2;
console.log(thing.size); // 2.2
Index Signatures
In JavaScript, you use [] to manipulate object properties, which JavaScript will read using toString. In the example below, using obj["name0"] works fine, but using obj[name1] will throw an error.
let obj = {
name0: "iris",
name1: "iris",
2: "iris"
};
console.log(obj["name0"]); // iris
console.log(obj[2]); // iris
console.log(obj[name1]); // error: name1 is not defined
In TypeScript, it will force you to use toString, reducing errors. TypeScript's Index Signatures must be of type string or number.
let obj = {
toString() {
console.log('toString called');
return 'Hello';
}
};
class Foo {
constructor(public message: string) {}
log() {
console.log(this.message);
}
}
let foo: any = {};
foo['Hello'].log(); // World
foo[obj] = new Foo('World'); // error: Type '{ toString(): string; }' cannot be used as an index type.
For more information on Index Signatures, refer to Day16.
Thank you for reading! See you tomorrow!
References
https://www.typescriptlang.org/docs/handbook/2/classes.html https://willh.gitbook.io/typescript-tutorial/advanced/class#typescript-zhong-lei-bie-de-yong-fa
