TS 的类,如何使用

答:

类是面向对象程序设计(OOP)实现信息封装的基础。

TS 定义类

class Car {
  // 字段
  engine: string

  // 构造函数
  constructor(engine: string) {
    this.engine = engine
  }

  // 方法
  disp(): void {
    console.log('发动机为 :   ' + this.engine)
  }
}

继承

使用 extends 关键字继承。子类可以对父类的方法重新定义,这个过程称为方法的重写。通过 super 关键字直接引用父类,可以引用父类的属性和方法。

修饰符

TS 在 ES6 的基础上添加了三种修饰符:public、private、protected,以及只读修饰符 readonly。

class Square {
  static width = '100px'
}

console.log(Square.width) // 100px

抽象类

抽象类作为其他派生类的基类使用,抽象类一般不会直接被实例化。不同于接口,抽象类可以包含成员的实现细节。

abstract class Animal {
  abstract makeSound(): void
  move(): void {
    console.log('roaming the earth...')
  }
}

class Cat extends Animal {
  makeSound() {
    console.log('miao miao')
  }
}

const cat = new Cat()
cat.makeSound() // miao miao
cat.move()      // roaming the earth...

类也可以作为接口

类声明同时会创建一个同名类型,因此可以把类当作接口使用,常用于为组件 Props 之类的对象定义类型。

export default class Props {
  public children: Array<React.ReactElement> | React.ReactElement | never[] = []
  public speed: number = 500
  public height: number = 160
  public animation: string = 'easeInOutQuad'
  public isAuto: boolean = true
  public autoPlayInterval: number = 4500
  public selectedColor: string = ''
  public showDots: boolean = true
}

来源整理自:vue3js.cn 面试官系列