Unions and Intersection Types
Union Types
use |
union type limits the members we can access into the common fields of the two types
a usual way to use union type is to set a common field, do different stuff and access different other fields by checking the common field(maybe using switch)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 function func (param: string | number ) { ... }interface Bird { fly(): void ; layEggs(): void ; } interface Fish { swim(): void ; layEggs(): void ; } declare function getSmallPet ( ): Fish | Bird ;let pet = getSmallPet();pet.layEggs(); pet.swim(); type NetworkLoadingState = { state : "loading" ; }; type NetworkFailedState = { state : "failed" ; code: number ; }; type NetworkSuccessState = { state : "success" ; response: { title : string ; duration: number ; summary: string ; }; }; type NetworkState = | NetworkLoadingState | NetworkFailedState | NetworkSuccessState; function logger (state: NetworkState ): string { switch (state.state) { case "loading" : return "Downloading..." ; case "failed" : return `Error ${state.code} downloading` ; case "success" : return `Downloaded ${state.response.title} - ${state.response.summary} ` ; } }
Intersection Types
use &
intersection type allows to access all members of listed types
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 interface ErrorHandling { success : boolean ; error ?: { message : string }; } interface Data { stuffs : { title : string }[]; } type Response = Data & ErrorHandling;const respHandler = (resp: Response ) => { if (resp.error) { console .error(resp.error.message); return ; } console .log(resp.stuffs); }