TypeScript Classes
Working with classes in TypeScript
Basic Class
class User { # define class
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
Access Modifiers
class User {
public name: string; # accessible everywhere (default)
private password: string; # only in class
protected email: string; # in class and subclasses
}
Constructor Shorthand
class User {
constructor(
public name: string, # auto-assign properties
private age: number
) { }
}
Readonly Properties
class User {
readonly id: number; # cannot be changed after init
constructor(id: number) {
this.id = id;
}
}
Inheritance
class Person {
constructor(public name: string) { }
}
class Employee extends Person { # extend class
constructor(name: string, public id: number) {
super(name); # call parent constructor
}
}
Abstract Classes
abstract class Shape { # cannot be instantiated
abstract area(): number; # must be implemented
}
class Circle extends Shape {
area() { return 0; }
}