-
-
Save myericho/8307de18247944daf2a1a9b774dd0bc3 to your computer and use it in GitHub Desktop.
TypeScript - extend member type via generic and type intersection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 利用 TypeScript Generic & Type Intersection 擴充成員資料定義 | |
/** | |
* Base Class 宣告 obs 成員,且用泛型擴充 obs 型別定義 | |
*/ | |
class Base<T extends {}> { | |
obs: {} & T = <T>{}; | |
} | |
/** | |
* Child1 繼承 Base 對 obs 擴充一個 name 欄位 | |
*/ | |
class Child1<T> extends Base<{ name: string } & T> { | |
constructor() { | |
super(); | |
this.obs.name; | |
this.obs.id; | |
// Child1 沒有 id 欄位,所以 IntelliSense 會給予警告 | |
// [ts] Property 'id' does not exist on type '{ name: string; } & T'. | |
} | |
} | |
/** | |
* Child2 繼承 Base 對 obs 擴充另一個 id 欄位 | |
*/ | |
class Child2 extends Base<{ id: string }> { | |
constructor() { | |
super(); | |
this.obs.id; | |
} | |
} | |
/** | |
* Child3 繼承 Child1 又對 obs 擴充 address 欄位 | |
*/ | |
class Child3 extends Child1<{ address: string }> { | |
constructor() { | |
super(); | |
this.obs.name; | |
this.obs.address; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment