Class
Structure
/*
`extends` tells User is a sub-class of Account. (Only extends ONE class)
`implements` ensures that User comforms to these `interfaces` or `types`.
*/
class User extends Account implements Updatable, Serializable {
// The default property being public access, not optional and writable.
id: string;
// Defines a optional property, which can hold `undefined` or not exist at all.
middleName?: string;
/*
Defines a `trust me, it's there` property.
(Enforcing to the compiler that this cannot be optional)
*/
name!: string;
/*
Defines private properties, only accessible to current class.
*/
private attr: unknown; // Private only at compilation
#attr: unknown; // Private at compilation and runtime
// Defines a property with a default value.
role = "Student";
/*
Defines a readonly property.
Can only be set here at declaration or at the constructor.
*/
readonly createdAt: Date;
// See more at `constructor sections` bellow.
constructor() { ... }
/*
Describe class methods.
(Prefer using `arrow function` style to not impact the use of `this`)
More info bellow.
*/
setName(name: string) { this.name = name; }
checkName = (name: string) => { return this.name; }
// Overload method definitions
sync(): void;
sync(param: string): string;
// Getter and Setter of properties
get role() { return this.role.setUpperCase(); }
set role(value: "Student" | "Teacher") { this.role = value.setLowerCase(); }
/*
Make `private` or `protected` methods.
(`protected` are accessible to sub-classes)
*/
private makeRequest() { ... }
protected makeRequest() { ... }
// Define `static` properties or methods
static #userCount = 0; // static and private
static registerUser(user: User) { ... }
/*
Static blocks for setting up static variables.
(`this` refers to the static class)
*/
static {
this.#userCount = -1;
}
}constructor section
constructor sectionthis in classes
this in classesAbstract classes
Difference of Abstract class and Interface
Decorators and Attributes
Last updated