Typescript中interface與type的相同點(diǎn)與不同點(diǎn)的詳細(xì)說明
interface VS type
大家使用 typescript 總會使用到 interface 和 type,官方規(guī)范 稍微說了下兩者的區(qū)別
- An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot.
- An interface can have multiple merged declarations, but a type alias for an object type literal cannot.
但是沒有太具體的例子。
明人不說暗話,直接上區(qū)別。
相同點(diǎn)
都可以描述一個(gè)對象或者函數(shù)
interface
interface User {
name: string
age: number
}
interface SetUser {
(name: string, age: number): void;
}type
type User = {
name: string
age: number
};
type SetUser = (name: string, age: number)=> void;都允許拓展(extends)
interface 和 type 都可以拓展,并且兩者并不是相互獨(dú)立的,也就是說 interface 可以 extends type, type 也可以 extends interface 。 雖然效果差不多,但是兩者語法不同。
interface extends interface
interface Name {
name: string;
}
interface User extends Name {
age: number;
}type extends type
type Name = {
name: string;
}
type User = Name & { age: number };interface extends type
type Name = {
name: string;
}
interface User extends Name {
age: number;
}type extends interface
interface Name {
name: string;
}
type User = Name & {
age: number;
}不同點(diǎn)
type 可以而 interface 不行
- type 可以聲明基本類型別名,聯(lián)合類型,元組等類型
// 基本類型別名
type Name = string
// 聯(lián)合類型
interface Dog {
wong();
}
interface Cat {
miao();
}
type Pet = Dog | Cat
// 具體定義數(shù)組每個(gè)位置的類型
type PetList = [Dog, Pet]- type 語句中還可以使用 typeof 獲取實(shí)例的 類型進(jìn)行賦值
// 當(dāng)你想獲取一個(gè)變量的類型時(shí),使用 typeof
let div = document.createElement('div');
type B = typeof div- 其他騷操作
type StringOrNumber = string | number;
type Text = string | { text: string };
type NameLookup = Dictionary<string, Person>;
type Callback<T> = (data: T) => void;
type Pair<T> = [T, T];
type Coordinates = Pair<number>;
type Tree<T> = T | { left: Tree<T>, right: Tree<T> };interface 可以而 type 不行
interface 能夠聲明合并
interface User {
name: string
age: number
}
interface User {
sex: string
}
/*
User 接口為 {
name: string
age: number
sex: string
}
*/總結(jié)
一般來說,如果不清楚什么時(shí)候用interface/type,能用 interface 實(shí)現(xiàn),就用 interface , 如果不能就用 type 。其他更多詳情參看 官方規(guī)范文檔
更多關(guān)于Typescript中interface與type的相關(guān)知識點(diǎn)請查看下面的相關(guān)鏈接
相關(guān)文章
JavaScript lastIndexOf方法入門實(shí)例(計(jì)算指定字符在字符串中最后一次出現(xiàn)的位置)
這篇文章主要介紹了JavaScript字符串對象的lastIndexOf方法入門實(shí)例,lastIndexOf方法用于計(jì)算指定字符在字符串中最后一次出現(xiàn)的位置,需要的朋友可以參考下2014-10-10
JavaScript 學(xué)習(xí)筆記(十四) 正則表達(dá)式
RegExp類 RegExp對象的構(gòu)造函數(shù)可以帶一個(gè)或兩個(gè)參數(shù) 第一個(gè)參數(shù)是描述需要進(jìn)行匹配的模式字符串,如果還有第二個(gè)參數(shù),這個(gè)參數(shù)則制定了額外的處理指令。2010-01-01
JavaScript字符串對象toLowerCase方法入門實(shí)例(用于把字母轉(zhuǎn)換為小寫)
這篇文章主要介紹了JavaScript字符串對象toLowerCase方法入門實(shí)例,toLowerCase方法用于把字母字符串轉(zhuǎn)換為小寫形式,需要的朋友可以參考下2014-10-10
javascript獲得當(dāng)前的信息的一些常用命令
這篇文章主要介紹了javascript獲得當(dāng)前的信息的一些常用命令,需要的朋友可以參考下2015-02-02

