Skip to content

interface 和 type 的区别 ​

2022-11-09 16:21:28

interface 和 type 都是 ts 中定义类型的关键字,他们在功能上比较相似,但还是有一些差别

type ​

类型别名,为一些类型的组合起一个别名,可以为任意数据做类型约束,不支持多次声明

interface ​

接口,只能为对象结构的数据做类型约束

interface 支持声明合并,多个同名的 interface 的属性会合并为一个

ts
interface Person {
  name: string
}
interface Person {
  age: number
}
const person: Person = {
  name: 'zhangsan',
  age: 18
}

注意:同名的属性不会被直接覆盖,而是会报错

interface 可以继承另一个 interface,在现有的基础上再去新增其他属性 也可以继承对象结构的 type

ts
type Person = {
  age: number
}
interface OtherPerson extends Person {
  name: string
}
interface AnotherPerson extends OtherPerson {
  address: string
}

const person: AnotherPerson = {
  name: 'zhangsan',
  age: 18,
  address: 'Shanghai'
}

Released under the MIT License.