typeScript
interface和type的區(qū)別
interface 和 type 很相似,很多時(shí)候,用兩種方式都能實(shí)現(xiàn)。
- 類型別名可以用于其它類型 (聯(lián)合類型、元組類型、基本類型(原始值)),interface不支持
type PartialPointX = { x: number };
type PartialPointY = { y: number };
// union(聯(lián)合)
type PartialPoint = PartialPointX | PartialPointY;
// tuple(元祖)
type Data = [PartialPointX, PartialPointY];
//primitive(原始值)
type Name = Number;
// typeof的返回值
let div = document.createElement('div');
type B = typeof div;
- interface 可以多次定義 并被視為合并所有聲明成員。type 不支持
interface Point {
x: number;
}
interface Point {
y: number;
}
const point: Point = { x: 1, y: 2 };
- type 能使用 in 關(guān)鍵字生成映射類型,但 interface 不行。
type Keys = 'firstname' | 'surname';
type DudeType = {
[key in Keys]: string;
};
const test: DudeType = {
firstname: 'Pawel',
surname: 'Grzybek',
};
- 默認(rèn)導(dǎo)出方式不同
// inerface 支持同時(shí)聲明,默認(rèn)導(dǎo)出 而type必須先聲明后導(dǎo)出
export default interface Config {
name: string;
}
// 同一個(gè)js模塊只能存在一個(gè)默認(rèn)導(dǎo)出哦
type Config2 = {name: string}
export default Config2