Last updated on Oct 2, 2022
type 和 interface 非常相似,在很多情况下你可以在它们之间自由选择。几乎所有 interface 的功能都可以在 type 中使用,关键的区别在于,type 不能被重新打开以添加新的属性,而 interface 则总是可以扩展的。
type Name = string),联合类型 |,元祖 [] 等类型interface
type
向现有接口添加新字段(声明合并。接口可被定义多次)
interface Window {
title: string
}
interface Window {
ts: TypeScriptAPI
}
/** 接口为:
interface Window {
title: string
ts: TypeScriptAPI
}
*/
const src = 'const a = "Hello World"'
window.ts.transpileModule(src, {})
创建后无法更改类型
type Window = {
title: string
}
type Window = { // Error: Duplicate identifier 'Window'.
ts: TypeScriptAPI
}
// Error: Duplicate identifier 'Window'.
extends 拓展 interface
interface Animal {
name: string
}
interface Bear extends Animal {
honey: boolean
}
type Name = {
name: string
}
interface User extends Name {
age: number
}
「类型交叉」拓展 type
type Animal = {
name: string
}
type Bear = Animal & {
honey: boolean
}
interface Name {
name: string
}
type User = Name & {
age: number
}
公共的用 interface 实现,不能用 interface 实现的再用 type 实现