Typescript 区分 type 和 interface

590 阅读1分钟

type 和 interface 的区别

  1. 声明函数方式不一样
type func = (x: str): void
interface Ifunc {
	(x:string): void
}
  1. type 可以声明基本类型、联合类型和元组,interface 不行
// primitive
type Name = string;

// object
type PartialPointX = { x: number; };
type PartialPointY = { y: number; };

// union
type PartialPoint = PartialPointX | PartialPointY;

// tuple
type Data = [number, string];
  1. 继承 type 和 interface 不是互斥的,可以相互继承
// interface
interface PartialPointX { x: number; }
interface Point extends PartialPointX { y: number; }

// type
type PartialPointX = { x: number; };
type Point = PartialPointX & { y: number; };

// interface extends type
type PartialPointX = { x: number; };
interface Point extends PartialPointX { y: number; }

// type extends interface
interface PartialPointX { x: number; }
type Point = PartialPointX & { y: number; };
  1. 实现
interface Point {
  x: number;
  y: number;
}

class SomePoint implements Point {
  x: 1;
  y: 2;
}

type Point2 = {
  x: number;
  y: number;
};

class SomePoint2 implements Point2 {
  x: 1;
  y: 2;
}

type PartialPoint = { x: number; } | { y: number; };

// FIXME: can not implement a union type
class SomePartialPoint implements PartialPoint {
  x: 1;
  y: 2;
}
  1. 声明合并

interface 可以 type不行

利用 type 特性,可以做的一些 interface 做不到的事

  1. 创建一颗tree
type Tree<T> = T & { parent: Tree<T> };
  1. 声明一个非空的类型
type NonNullable<T> = T extends null | undefined ? never : T;

参考链接