We talked about TypeScript objects in the previous chapter. After that, we talk about TypeScript classes. A class is a template for an object that describes the common properties and methods of the objects it creates. The syntax for creating a class looks like this
Class className {attribute constructor method}Copy the code
For example,
class Animal {
/ / property
name: string
color: string
constructor(name: string, color: string) {
this.name = name;
this.color = color;
}
/ / method
run() {
console.log("Animals can run...")}}Copy the code
-
The static keyword, used to define the class’s data members (properties and methods) as static. Static members and methods can be called directly from the class name. For example,
class Dog { / / property static color: string static show() { console.log('I'm a dog${Dog.color}The dog `) } } Dog.color = "White" Dog.show(); Copy the code
-
Access control modifier
In TypeScript, access control characters are used to protect access to classes, variables, methods, and constructors. TypeScript supports three different access rights.
-
Public (default) : public and can be accessed anywhere.
-
Protected: It is protected and can be accessed by itself as well as by its subclasses and superclasses.
-
Private: private, accessible only by the class in which it is defined.
-
-
-
Class inheritance
TypeScript supports class inheritance, which means that when you create a class, you can inherit from an existing class. The existing class is called a parent class, and classes that inherit from it are called subclasses.
Class inheritance uses the extends keyword. Subclasses can inherit anything except the private members (methods and properties) and constructors of their parent class.
Note: TypeScript inherits only one class at a time, not multiple classes. For example,
class Animal { / / property name: string color: string constructor(name: string, color: string) { this.name = name; this.color = color; } / / method run() { console.log("Animals can run...")}}// Cat inherits Animal name and color attributes from its parent class Cat extends Animal { call() { console.log(I was `The ${this.name}My color isThe ${this.color}`); }}let cat = new Cat("Mimi"."White"); cat.call(); Copy the code