TypeScript Classes

Classes

1
2
3
4
5
6
7
8
9
10
11
class Greeter {
greeting: string

constructor(message: string) {
this.greeting = message
}

greet(): string {
return "Hello, " + this.greeting
}
}

Private

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Animal {
constructor(private name: string) {}
}

class Horse extends Animal {
constructor() {
super("Horse")
}
}

class Human {
constructor(private name: string) {}
}

let animal = new Animal("Lucy")
let horse = new Horse()
let human = new Human("Jack")
animal = horse // success
animal = human // failed

Protected

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Person {
protected name: string

protected constructor(name: string) {
this.name = name
}
}

class Employee extends Person {
private department: string

constructor(name: string, department: string) {
super(name)
this.department = department
}

public getInfo(): string {
return `name: ${this.name}, department: ${this.department}`
}
}

let Edward = new Employee("Edward", "front-end")
let person = new Person("Jack") // failed
console.log(Edward.getInfo())

Readonly modifier

1
2
3
4
5
6
7
8
9
10
class C {
readonly name: string
readonly length: number = 8

constructor(name: string) {
this.name = name
}
}

new C("test").name = "test1" // failed

Accessors

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const MAX = 10

class Person {
private _fullName: string
get fullName(): string {
return this._fullName
}

set fullName(name: string) {
if (name && name.length > MAX) {
throw new Error("too long")
}
this._fullName = name
}
}

new Person().fullName = "Edward"

Static Properties

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Point {
static origin = {x: 0, y: 0};

constructor(public scale: number) {
}

calculateDistance(point: { x: number, y: number }): number {
let xDist = (point.x - Point.origin.x);
let yDist = (point.y - Point.origin.y);
return Math.sqrt(xDist ** 2 + yDist ** 2);
}
}

let point1 = new Point(1, 0);
console.log(point1.calculateDistance({10, 20}));

Abstract Classes

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
abstract class Department {
constructor(public name: string) {}

printName(): void {
console.log("name: " + this.name)
}

abstract printMeeting(): void
}

class AccountingDepartment extends Department {
constructor() {
super("AccountingDepartment")
}

printMeeting(): void {
console.log("This is Accounting Department")
}

foo(): void {
console.log("foo")
}
}

let department: Department = new Department() // error: can not create an instance of an abstract class
let department2: Department = new AccountingDepartment()
department2.foo() // error: method doesn't exist on declared abstract type

Using a class as an interface

1
2
3
4
5
6
7
8
9
10
class Point {
x: number
y: number
}

interface point3D extends Point {
z: number
}

const point: point3D = { x: 0, y: 0, z: 0 }