Created
October 4, 2021 13:16
-
-
Save peerhenry/07aea7e6452ed8473477828c6d469527 to your computer and use it in GitHub Desktop.
Gekke type-shit in Typescript
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
| // Gekke type-shit in Typescript | |
| // duck typing | |
| // interface IFoo { | |
| // toString: () => string | |
| // } | |
| type ToStringable = { myToString: () => string } | |
| function loggo<T extends ToStringable>(x: T) { | |
| console.log(x.toString()) | |
| } | |
| // number, string, array, object literals, promise, | |
| // loggo('pietje') | |
| // loggo([1,2,3]) | |
| // loggo({}) | |
| // loggo(1234) | |
| // loggo({ foo: 'foo', myToString() { return this.foo } }) | |
| // loggo(new Promise(() => {})) | |
| // loggo(Infinity) | |
| // loggo(NaN) | |
| // mapped types | |
| const auto = { | |
| color: 'green', | |
| dom: new Date(), | |
| weight: 50, | |
| } | |
| type AutoMobile = typeof auto | |
| type AutoMobileSetter = { | |
| [K in keyof AutoMobile as `set${Capitalize<K>}`]: (v: AutoMobile[K]) => void | |
| } | |
| type AutoMobileGetter = { | |
| [K in keyof AutoMobile as `get${Capitalize<K>}`]: () => AutoMobile[K] | |
| } | |
| // in | |
| type Bird = { | |
| [K in 'fly' | 'quack']: () => void | |
| } | |
| // type query: keyof typeof | |
| type DateKey = keyof Date & symbol | |
| console.log(new Date()[Symbol.toPrimitive]('string')) | |
| console.log(new Date()[Symbol.toPrimitive]('number')) | |
| console.log(new Date()[Symbol.toPrimitive]('default')) | |
| // template literals | |
| type GetDrink = `get${'White' | 'Dark' | 'Green'}${'Whine' | 'Beer'}` | |
| type DateToKey = keyof Date & `to${string}` | |
| // indexable types | |
| type DateDic = { [k: string]: Date } | |
| // indexed type access | |
| type TrainStationApi = { fetchTrain: (track: string) => Promise<string> } | |
| type FetchTrain = TrainStationApi['fetchTrain'] | |
| // combine them! | |
| type DocumentQueryKey = keyof Document & `query${string}` | |
| type DocQ = { [k in DocumentQueryKey]: Document[k] } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment