typescript: abstract class 对比 interface

367 阅读1分钟

将代码拷贝到操练场查看报错或警告,可以帮助理解。 ---> playground

  1. 申明
interface A1 {
    b: 'Hello' // (property) A1.b: "Hello"
    changeB(s: string): void
}

abstract class A2 {
    b = 'hello world' // (property) A2.b: string
    changeB(s: string) {
      this.b = s
    }
}

这里可以这么理解,interface是一个无状态的类型,申明之后就是不变的,所以这里的b类型是Hello而不是string,而abstract是可以有状态的。

  1. extends

    • class不能 extends interface,但可以 extends abstract class
    • interface 可以 extends interface, 也可以 extends abstract class,甚至class
interface A1Interface {
    b: string
    changeB(s: string): void
}
// Cannot extend an interface 'A1Interface'. Did you mean 'implements'?
class A1d extends A1Interface {}
// can extend
interface A1e extends A1Interface{}

abstract class A2Class {
    b = 'hello' // 必须在申明或者构造函数中初始化
    changeB(s: string) {}
}
// can extend
class A2d extends A2Class {
    changeB(s: string) {
        this.b = s
    }
}
// can extend
interface A2f extends A2Class {}

  1. implements?

It’s important to understand that an implements clause is only a check that the class can be treated as the interface type. It doesn’t change the type of the class or its methods at all.

这是官网上一句话,意思是implement只是检测该类可以不可以看做实现了某个接口,不会改变类的类型和方法。从这句话可以看出两个信息:

  • 只有class才能应用implement
  • implement可以看成是约束,而extends才会能力增强
interface A1Interface {
    b: string
    changeB(s: string): void
}
// Interface declaration cannot have 'implements' clause.
interface A1e implements A1Interface{}
// can implement
class A1m implements A1Interface {
    b = 'hello'
    changeB(s: string) {
        this.b = s
    }
}

abstract class A2Class {
    b = 'hello implements'
    changeB(s: string) {}
}
// Interface declaration cannot have 'implements' clause
interface A2f implements A2Class {}
// can implement
class A1n implements A2Class {
    b = 'hello'
    changeB(s: string) {
        this.b = s
    }
}