你們使用 typescript 總會使用到 interface 和 type,官方規範 稍微說了下二者的區別java
- 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.
可是沒有太具體的例子。git
明人不說暗話,直接上區別。github
interface User {
name: string
age: number
}
interface SetUser {
(name: string, age: number): void;
}
複製代碼
type User = {
name: string
age: number
};
type SetUser = (name: string, age: number)=> void;
複製代碼
interface 和 type 均可以拓展,而且二者並非相互獨立的,也就是說 interface 能夠 extends type, type 也能夠 extends interface 。 雖然效果差很少,可是二者語法不一樣。typescript
interface Name {
name: string;
}
interface User extends Name {
age: number;
}
複製代碼
type Name = {
name: string;
}
type User = Name & { age: number };
複製代碼
type Name = {
name: string;
}
interface User extends Name {
age: number;
}
複製代碼
interface Name {
name: string;
}
type User = Name & {
age: number;
}
複製代碼
// 基本類型別名
type Name = string
// 聯合類型
interface Dog {
wong();
}
interface Cat {
miao();
}
type Pet = Dog | Cat
// 具體定義數組每一個位置的類型
type PetList = [Dog, Pet]
複製代碼
// 當你想獲取一個變量的類型時,使用 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 可以聲明合併數組
interface User {
name: string
age: number
}
interface User {
sex: string
}
/*
User 接口爲 {
name: string
age: number
sex: string
}
*/
複製代碼
通常來講,若是不清楚何時用interface/type,能用 interface 實現,就用 interface , 若是不能就用 type 。其餘更多詳情參看 官方規範文檔bash