09 TypeScript 中interface 与 abstract 的区别

395 阅读1分钟

基础

interface 与 abstract 使用目的?

为了提取对象类型中的关键类型声明,忽略代码的实现细节

// 基本语法
interface Car {
  getName: () => string 
}

abstract class Base {
    abstract getName() string
}

const b1 = new Base() // 报错不能通过 abstract class 实例化对象

区别

interface 与 abstract 区别是什么?

主要区别是 abstract 与 extends联合使用
interface 与 implements联合使用

  // 区别
  abstract class Base {
    abstract getName(): string;
  }

  interface Base2 {
    getName(): string;
  }
  // 通过关键字 extends
  class Derived extends Base {
    getName() {
      return "world";
    }
  }

  // 通过关键字 implements
  class Derived1 implements Base2 {
    getName() {
      return "world";
    }
  }
  const d = new Derived();
  d.getName();

abstract如何抽离new操作符参数?

abstract new (...args: any) => any抽离出 new 操作符参数

 // 抽离new操作符参数
  type ConstructorGeneric<T extends abstract new (...args: any) => any> =
    T extends abstract new (...args: infer P) => any ? P : never;

  interface Book {
    new (author: string, title: string): void;
  }

  type T1 = ConstructorGeneric<Book>;

image.png

abstract 使用场景?

除了 abstract new (...args: any) => any抽离出 new 操作符参数
尽量使用 interface type