TS中:type和interface的区别是什么?

37 阅读1分钟

一般来说,跟对象相关,习惯性用interface,跟对象不相关,用type

官方给出的文档说明:

1. 组合方式:interface使用extends来实现继承,type使用&来实现交叉类型。

interface B{
    b:string
}
interface A extends B{
    a:string
}

const a: A = {
    a:'hi',
    b:'hi'
}

// type:
type BB = {
    bb:string
}
type AA = {
    aa:string
} & BB

const aa:AA = {
    aa: 'hi',
    bb: 'hi'
}

2. 扩展方式:interface可以重复声明用来扩展,type一个类型只能声明一次

interface A {
    a: string
}

interface A{
    b: string
}

const a: A = {
    a:'hi',
    b:'hi'
}

//type:
type B = {
    a: string
}

type B = {
    b: string
}// 会报错,不能再改写

3. 范围不同:type 适用于基本类型,interface一般不行

type UserName = string

interface UserName2 extends string //报错

4. 命名方式不同:interface会创建新的类型名,type只是创建类型别名,但没有创建新的类型。

type X = number
const x: X = 1
type Y = typeof x // Y === X

关于as的补充

const a1 = [1,2,3] //此时类型为a1:number[]

const a2 = [1,2,3] as const //此时类型为a2: readonly [1,2,3]
type A = typeof a1
const b: A = [2,3,4] //会报错,只接收[1,2,3]