type 和 interface 的不同

1. type 可以用于描述基础类型, interface 不可以

补充:type 可以声明基本类型别名、联合类型 (string | number)、元组类型、映射类型等;而 interface 只能描述对象(包括函数)的形状,不能直接给原始类型起别名。

type Name = string
type Point = [number, number]
type Status = 'pending' | 'success' | 'error'

2. interface 可以同名合并类型, type 不可以

补充:同一个作用域内多次声明同名 interface 会自动合并成员,适合做声明合并(Declaration Merging),常用于给第三方类型扩展属性;type 重复声明会报错。

interface User { name: string }
interface User { age: number }
// User => { name: string; age: number }

3. 扩展类型的语法: interface 使用 extends , type 使用 &

interface Animal { name: string }
interface Dog extends Animal { bark(): void }

type Animal2 = { name: string }
type Dog2 = Animal2 & { bark(): void }

4. type 可以使用 typeof 来描述类型

const config = { host: 'localhost', port: 8080 }
type Config = typeof config  // { host: string; port: number }

补充:interface 也可以用 extends 继承一个 type (前提是 type 描述的是对象类型);type 也可以通过 & 继承 interface。两者在大多数场景下可互换,习惯上:用 interface 描述对象/类的契约;用 type 描述联合类型、元组、映射类型以及需要 typeof/class 取值的场景。

来源整理自:vue3js.cn 面试官系列