type 和 interface 的区别是什么?

181 阅读1分钟

一般我选择的是,和对象相关的,使用interface,和对象不相关的使用type

  1. 组合方式:interface 使用 extends 来实现继承,type 使用 & 来实现交叉类型。
insterface B {
    b: string
}
insterface A extends B {
    a: string
}
const a: A = {
    a: 'hi',
    b: 'hi'
}
=================================================================
type BB = {
    bb: string
}
type AA = {
    aa: string
} & BB

const aa: AA = {
    aa: 'hi',
    bb: 'hi'
}
  1. 扩展方式:interface 可以重复声明用来扩展,type 一个类型只能声明一次
// 1.js
insterface A {
    a: string
}
// 2.js
insterface A {
    b: string
}
const a: A = {
    a: 'hi',
    b: 'hi'
}
=========================================================
// 1.js
type A = {
    a: string
}
// 2.js
type A = {
    b: string
}
// 报错:Duplicate identifier 'A'.(2300)
有点像 const

  1. 范围不同:type 适用于基本类型,interface 一般不行。
type UserName:string = 'zs'
insterface 无法实现UserName是一个string类型
  1. 命名方式:interface 会创建新的类型名,type 只是创建类型别名,并没有新创建类型。