# Class 类型

在这里我们只关注 class 的类型,关于其他于 es6 的异同点也会稍微提及。

# 实现接口

interface Pingable {
  ping(): void;
}

class Sonar implements Pingable {
  ping() {
    console.log("ping!");
  }
}

# readonly

只能在构造函数中修改

class Greeter {
  readonly name: string = "world";

  constructor(otherName?: string) {
    if (otherName !== undefined) {
      this.name = otherName;
    }
  }
}

# Getters / Setters

class 的访问器属性

class C {
  _length = 0;
  get length() {
    return this._length;
  }
  set length(value) {
    //可以搞的复杂一些
    this._length = value;
  }
}

# extends

继承

class Animal {
  move() {
    console.log("Moving along!");
  }
}

class Dog extends Animal {
  woof(times: number) {
    for (let i = 0; i < times; i++) {
      console.log("woof!");
    }
  }
}

# 重载

class Base {
  greet() {
    console.log("Hello, world!");
  }
}

class Derived extends Base {
  greet(name?: string) {
    if (name === undefined) {
      super.greet();
    } else {
      console.log(`Hello, ${name.toUpperCase()}`);
    }
  }
}

# 成员可见

# public

公共

# protected

保护,只有派生类和自己可以访问

# private

私有,只有自己可以访问

只会用于 ts 的检测阶段,并不会参与 js 的运行时

# Static Members

class MyClass {
  static x = 0;
  static printX() {
    console.log(MyClass.x);
  }
}