Created
June 3, 2020 07:43
-
-
Save AfonsoTsukamoto/7d82263f7a098a2841ac32f40baabd39 to your computer and use it in GitHub Desktop.
Utility types for immutable js with typescript
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
// import types: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html#import-types | |
// allow us to import types on global type definitions | |
// To use, eg, for a map of User: | |
// type UserMap = ImmutableMap<User>; | |
interface ImmutableMap<T> extends import('immutable').Map<string, any> { | |
get<K extends keyof T>(name: K): T[K]; | |
} | |
type ImmutableMapList<T> = import('immutable').List<ImmutableMap<T>>; | |
type ImmutableUtilType<T = {}> = ImmutableMap<T> | ImmutableMapList<T>; | |
// eg: if we have | |
// const user: User = someuser; | |
// const foo: ImmutableMap<User> = Map(user); | |
// then we can get the User type back using from Immutable like: | |
// const sameUser: FromImmutable<typeof foo> = foo.toJS(); | |
// sameUSer will be of type User | |
type FromImmutable<T> = T extends ImmutableMap<infer U> ? U : T extends ImmutableMapList<infer V> ? V[] : never; | |
// This type takes an interface and if any of it's types extends a ImmutableType we unpack it | |
// Using directly ImmutableUtilType and FromImmutable doesn't seem to work everytime for some reason for which | |
// I currently don't have the time to research | |
// TODO: dry | |
type FromImmutableToJS<T> = { | |
[P in keyof T]: T[P] extends ImmutableMapList<infer U> ? U[] : T[P] extends ImmutableMap<infer V> ? V : T[P] | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment