extends
是 typeScript 中的關(guān)鍵字。在 typeScript 的類型編程世界里面,它所扮演的角色實(shí)在是太重要了,所以,我們不得不需要重視它,深入學(xué)習(xí)它。在我看來(lái),掌握它就是進(jìn)入高級(jí) typeScript 類型編程世界的敲門(mén)磚。但是,現(xiàn)實(shí)是,它在不同的上下文中,具體不同的,相差很大的語(yǔ)義。如果沒(méi)有深入地對(duì)此進(jìn)行梳理,它會(huì)給開(kāi)發(fā)者帶來(lái)很大的困惑。梳理并深入學(xué)習(xí)它,最后掌握它,這就是我編寫(xiě)這篇文章的初衷。
extends 的幾個(gè)語(yǔ)義
讓我們開(kāi)門(mén)見(jiàn)山地說(shuō)吧,在 typeScript 在不同的上下文中,extends
有以下幾個(gè)語(yǔ)義。不同語(yǔ)義即有不同的用途:
- 用于表達(dá)類型組合;
- 用于表達(dá)面向?qū)ο笾小割悺沟睦^承
- 用于表達(dá)泛型的類型約束;
- 在條件類型(conditional type)中,充當(dāng)類型表達(dá)式,用于求值。
extends 與 類型組合/類繼承
extends
可以跟 interface
結(jié)合起來(lái)使用,用于表達(dá)類型組合。
示例 1-1
interface ChildComponentProps { onChange: (val: string)=> void } interface ParentComponentProps extends ChildComponentProps { value: string }
在 react 組件化開(kāi)發(fā)模式中,存在一種自底向上的構(gòu)建模式 – 我們往往會(huì)先把所有最底層的子組件的 props
構(gòu)建好,最后才定義 container component
(負(fù)責(zé)提升公共 state,聚合和分發(fā) props) 的 props
。此時(shí),inferface 的 extends
正好能表達(dá)這種語(yǔ)義需求 – 類型的組合(將所有子組件的 props
聚合到一塊)。
當(dāng)然,interface
的 extends
從句是可以跟著多個(gè)組合對(duì)象,多個(gè)組合對(duì)象之間用逗號(hào),
隔開(kāi)。比如ParentComponentProps
組合多個(gè)子組件的 props
:
示例 1-2
interface ChildComponentProps { onChange: (val: string)=> void } interface ChildComponentProps2 { onReset: (value: string)=> void } interface ParentComponentProps extends ChildComponentProps, ChildComponentProps2 { value: string }
注意,上面指出的是「多個(gè)組合對(duì)象」,這里也包括了Class
。對(duì),就是普通面向概念中的「類」。也就是說(shuō),下面的代碼也是合法的:
示例 1-3
interface ChildComponentProps { onChange: (val: string)=> void } interface ChildComponentProps2 { onReset: (value: string)=> void } class SomeClass { private name!: string // 變量聲明時(shí),變量名跟著一個(gè)感嘆號(hào)`!`,這是「賦值斷言」的語(yǔ)法 updateName(name:string){ this.name = name || '' } } interface ParentComponentProps extends ChildComponentProps, ChildComponentProps2, SomeClass { value: string }
之所以這也是合法的,一切源于一個(gè)特性:在 typeScript 中,一個(gè) class 變量既是「值」也是「類型」。在interface extends class
的上下文中,顯然是取 class 是「類型」的語(yǔ)義。一個(gè) interface extends
另外一個(gè) class,可以理解為 interface 拋棄這個(gè) class 的所有實(shí)現(xiàn)代碼,只是跟這個(gè) class 的「類型 shape」 進(jìn)行組合。還是上面的示例代碼中,從類型 shape 的角度,SomeClass
就等同于下面的 interface:
示例 1-4
interface SomeClass { name: string updateName: (name:string)=> void }
好了,