Last active
October 28, 2019 14:18
-
-
Save emptyother/e9258f0851e989b37942dbc1787e1e55 to your computer and use it in GitHub Desktop.
Useful typescript interfaces
This file contains 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
/** | |
* Removes ReadOnly from all properties on an interface. | |
*/ | |
type Mutable<T> = { | |
-readonly [P in keyof T]: T[P] extends ReadonlyArray<infer U> ? Mutable<U>[] : Mutable<T[P]> | |
}; |
This file contains 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
/** | |
* A per-item typed `Map` object. | |
* @author /r/mcaruso | |
* @see https://www.reddit.com/r/typescript/comments/dn2xzd/typing_a_map/ | |
*/ | |
interface MapObject<Props extends object> extends Map<keyof Props, Props[keyof Props]> { | |
get<K extends keyof Props>(key : K) : Props[K]; | |
set<K extends keyof Props>(key : K, val: Props[K]): this; | |
forEach<K extends keyof Props>(callbackfn: (value: Props[K], key: K, map: any) => void, thisArg?: any): void; | |
has<K extends keyof Props>(key: K): boolean; | |
delete<K extends keyof Props>(key: K): boolean; | |
} | |
/** | |
* How to use: | |
*/ | |
// Force type: | |
const map = new Map() as MapObject<{ imgur: ImageData; twitter: string; }>; | |
// Works: | |
map.set('twitter', 'final'); | |
// Error as expected: | |
map.set('imgur', 3); | |
// Returns a ImageData: | |
var s = map.get('imgur'); | |
// Returns a string: | |
var t = map.get('twitter'); | |
map.forEach((value, key, map) => { | |
// Unfortunately I'm unable to find a way for foreach to reduce the type on asserting the key content: | |
if(key === 'twitter') { | |
var f = value; // string | ImageData | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment