跳至主要內容

类类型

Mr.He2022年1月16日大约 3 分钟TypeScriptclass

类类型

类定义

// 类声明
class ClassName {
  // ...
}

// 类表达式
const Circle = class {
  // ...
};

类的使用

在开发过程中,任何实体都可以被抽象为一个使用类表达的类似对象的数据结构,这个数据结构既包含属性,又包含方法。

class Point {
  x: number;
  y: number;
  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }
  getPosition() {
    return `(${this.x}, ${this.y})`;
  }
}

const point = new Point(1, 2);
point.getPosition(); // (1, 2)

抽象类的使用

abstract class People {
  constructor(public name: string) {}
  abstract printName(): void;
}
class Man extends People {
  constructor(name: string) {
    super(name);
    this.name = name;
  }
  printName() {
    console.log(this.name);
  }
}
const m = new Man(); // error Expected 1 arguments, but got 0.
const man = new Man("TypeScript");
man.printName(); // 'TypeScript'
const p = new People("TypeScript"); // error Cannot create an instance of an abstract class.

这里定义了一个抽象类 People,在抽象类里定义 constructor 方法必须传入一个字符串类型参数,并把这个 name 参数值绑定在创建的实例上; 使用 abstract 关键字定义一个抽象方法 printName,这个定义可以指定参数,指定参数类型,指定返回类型。

当直接使用抽象类 People 实例化的时候,就会报错,只能创建一个继承抽象类的子类,使用子类来实例化。

存取器

class C {
  private _foo: number = 0;
  get foo(): number {
    return this._foo;
  }
  set foo(value: number) {
    if (value >= 0) {
      this._foo = value;
    }
  }
}

类的修饰符

public (默认是 public)

public 表示公共的,用来指定在创建实例后可以通过实例访问的

class Foo {
  public a: string = "";
}

class Bor extends Foo {
  b() {
    return this.a; //允许访问
  }
}

const b = new Bor();
b.a; //允许访问
b.b(); //允许访问

protected

protected 修饰的成员在继承该类的子类中可以访问

class Foo {
  protected x: string = "";

  a() {
    this.x; // 允许访问
  }
}

class Bor extends Foo {
  b() {
    return this.x; //允许访问
  }
}

const b = new Foo();
b.x; //不允许访问

private

保护对象在当前类和派生类内部访问, 类的定义外面是没法访问的

class Foo {
  private x: string = "";

  a() {
    this.x; // 允许访问
  }
}

class Bor extends Foo {
  b() {
    return this.x; //不允许访问
  }
}

const b = new Foo();
b.x; //不允许访问

const c = new Bor();
c.x; // 不允许访问

只读修饰符

class UserInfo {
  readonly name: string;
  constructor(name: string) {
    this.name = name;
  }
}
const user = new UserInfo("TypeScript");
user.name = "haha"; // error Cannot assign to 'name' because it is a read-only property
  1. 严格模式在函数中初始化,需要增加非空类型断言
class A {
  a!: number;
  // ! 非空断言,才可以
  init() {
    this.a = 0;
  }

  constructor() {
    this.init();
  }
}

类类型接口

implements 关键字用来指定一个类要继承的接口, 如果是接口和接口、类和类直接的继承,使用 extends, 如果是类继承接口,则用 implements。

虽然一个类只允许继承一个基类,但是可以实现多个接口

interface A {
  radius: number;
}
interface B {
  area(): number;
}

class C implements A, B {
  radius: number = 5;

  area(): number {
    return Math.PI * this.radius * this.radius;
  }
}

静态成员

静态成员不属于类的实例,而是属于类本身

class Circle {
  static version: string = "1.0.1";
}

const version = Circle.version; // OK

const circle = new Circle();
circle.version; // 编译错误!