欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Typescript 中的 interface 和 type 到底有什么區(qū)別詳解

 更新時間:2019年06月18日 10:14:51   作者:七月流螢  
這篇文章主要介紹了Typescript 中的 interface 和 type 到底有什么區(qū)別詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(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)

都可以描述一個對象或者函數(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ù)組每個位置的類型
type PetList = [Dog, Pet]

type 語句中還可以使用 typeof 獲取實(shí)例的 類型進(jìn)行賦值

// 當(dāng)你想獲取一個變量的類型時,使用 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é)

一般來說,如果不清楚什么時候用interface/type,能用 interface 實(shí)現(xiàn),就用 interface , 如果不能就用 type 。其他更多詳情參看 官方規(guī)范文檔

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論