class的类型

如何给 calss 添加类型说明:

  1. 实例属性的类型首先列出来,表示this对象上有此属性
  2. 类可以当做接口使用,相当于new 以后的实例类型 ``typescript class Animal { name: string; // 1 constructor(name: string) { this.name = name; } sayHi(): string { returnMy name is ${this.name}`; } }

let a: Animal = new Animal(‘Jack’); // 2 console.log(a.sayHi()); // My name is Jack

  1. <a name="pSBQt"></a>
  2. # class implements interface (类实现接口)
  3. 通过 implements 可以把接口的属性加到类中
  4. ```typescript
  5. interface Alarm {
  6. alert(): void;
  7. }
  8. class Car implements Alarm {
  9. alert() {
  10. console.log('Car alert');
  11. }
  12. }

interface extends class (接口继承类)

常见的面向对象语言中,接口是不能继承类的,但是在 TypeScript 中却是可以的,
因为在TS中声明 class 的时候同时会创建后一个同名类型,这个类型包含class 实例属性类型和方法类型,

  1. class Point {
  2. x: number;
  3. y: number;
  4. constructor(x: number, y: number) {
  5. this.x = x;
  6. this.y = y;
  7. }
  8. }
  9. let p:Point = { // {x:number; y:number}
  10. x:2,
  11. y:2
  12. }

所以interface extends class 实际上是 interface extends interface

  1. class Point {
  2. x: number;
  3. y: number;
  4. constructor(x: number, y: number) {
  5. this.x = x;
  6. this.y = y;
  7. }
  8. }
  9. interface PointInstanceType {
  10. x: number;
  11. y: number;
  12. }
  13. // 等价于 interface Point3d extends PointInstanceType
  14. interface Point3d extends Point {
  15. z: number;
  16. }
  17. let point3d: Point3d = {x: 1, y: 2, z: 3};