interface,class,和abstract class這3個概念,既有聯繫,又有區別,本文嘗試着結合官方文檔來闡述這三者之間的關係。html
Declaration Type | Namespace | Type | Value |
---|---|---|---|
Namespace | X | X | |
Class | X | X | |
Enum | X | X | |
Interface | X | ||
Type Alias | X | ||
Function | X | ||
Variable | X |
首先咱們來說一下上面這張表格,當咱們第一列的關鍵字進行聲明時,咱們在作什麼。typescript
namespace job { haircut(): void; } class Man{ name: string; } let imgss = new Man(); enum Color {red, blue, yellow} interface dogfood { brand: string; price: number } type event = 'mouse' | 'keyboard'; function foo(){} let a = 2; var b = {}; const c = null;
namespace用來聲明一個命名空間,比較著名的命名空間有lodash,裏面有一堆工具函數,通通放在一個叫_的namespace裏面,同時你也能夠let $ = _
;因此namespace也聲明瞭一個值。函數
class聲明瞭一個值,也聲明瞭一種類型,你能夠把Man賦值給一個變量,因此class是一種值,也能夠說imgss是一個Man(類型),此時Man承擔了一種類型的角色。工具
enum聲明瞭一個值,也聲明瞭一種類型。咱們說red是一種Color,Color在這裏承擔類型的角色,也能夠把Color賦值給一個變量this
interface聲明瞭一種類型,可是你不能把dogfood賦值給某個變量,不然你會獲得一個報錯``dogfood' only refers to a type, but is being used as a value here`spa
其餘function,let,var,const都在聲明一個值,你 不能說xxx是一個a,或者xxx是一個foo,不能把值當成類型使用。code
咱們知道,不算symbol,js中有6種基本類型,number,string,boolean,null, undefined, object。可是隻依靠這幾種類型,來描述某個函數須要傳什麼樣的參數,是遠遠不夠的,這也是interface的使命--描述一個值(value)的形狀(type)。htm
如今咱們來看class,class首先也具備interface的能力,描述一個形狀,或者說表明一種類型。此外class還提供了實現,也就是說能夠被實例化;ip
因此class能夠implements interface:文檔
interface ManLike { speak(): void; leg: number; hand: number; } class Human implements ManLike { leg: number = 2; hand: number = 2; speak() { console.log('i can speak'); } }
而interface能夠extends class,此時的class承擔類型的角色
interface Chinese extends Human { country: string; }
那麼interface能不能extends enum或者type alias呢,這兩個兄弟也聲明瞭type啊,答案是不行的,官方報錯的信息:
An interface can only extend an object type or intersection of object types with statically known members.
class和abstract class的區別主要是abstract class不能被實例化:
abstract Human { name: string; abstract lang(): void; toString() { return `<human:${this.name}>` } } new Human // Cannot create an instance of an abstract class.
二者都不能被實例化,可是abstract class 也能夠被賦值給變量。 interface 裏面不能有方法的實現,abstract class 能夠提供部分的方法實現,這些方法能夠被子類調用。