- type是類型
別名
,并不是真正的類型 - type 聲明一個帶屬性的函數(shù):
type FnWithProps = {
(a:number,b:number): number,
props: string
}
const fn: FnWithProps = (a,b) => a+b
fn.props = 'xxx'
-
interface
是聲明一個接口
配名,描述對象的屬性
interface X {
age: number
}
type A1 = Array<string> & {
name: string
} & X
等同于
interface A2 extends Array<string>,X {
name: string
}
- interface描述函數(shù)
interface FnWithProp {
(a:number,b:number): number
prop?: string
}
const fn:Fn = (a,b) => a+b
fn.prop = 'xxx'
- interface 描述日期渠脉,
類型里不能添加屬性了
interface D extends Date {}
const date: D = new Date()
- type不可以重新賦值
- interface可以重新賦值
總結(jié)區(qū)別:
- type是類型
別名
,并不是真正的類型芋膘,interface是類型聲明,具有真實效果 - type可以描述
任何類型
臂拓,interface只針對對象
- type
不可以
重復(fù)聲明习寸,interface可以
重復(fù)聲明,會自動合并
孵滞,即可以擴展
,比如在axios中擴展config的配置參數(shù)類型坊饶。因此寫庫
的時候一般用interface
殴蓬,方便擴展
;自己項目的時候一般用type
根蟹,防止被篡改
- type
交叉類型
功能類似于interface的繼承
- type功能相對來說更強大糟秘,
工具類型
都是用type來實現(xiàn)的