TypeScript type 关键字和 interface 关键字

发布时间 2023-04-15 19:34:34作者: Himmelbleu

前言

typeinterface 都可以声明 TS 类型。

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

interface Point2 {
  x: number;
  y: number;
};

它们两个声明这个对象类型有任何区别吗?很明显没有,我认为最能区分它们两个的标志是,type 有一个 = 赋值等号。

type

type 可以做类型运算,例如 TS 工具类型:

type Partial<T> = { [P in keyof T]?: T[P] | undefined; }

经过一系列 TS 类型运算,返回的结果赋值给 type 关键字声明的名称 Partial。TS 的工具类型都是由 type 关键字声明的。

type 可以声明联合类型、基本类型(string、boolean、number)、对象类型(Object、Function、Map 等)。

interface

下面是 interface 关键字的原文解释:

An interface declaration is another way to name an object type.

仔细品味,interface 关键字是另一种声明对象类型的方式。