Skip to content

Instantly share code, notes, and snippets.

@AfonsoTsukamoto
Created June 3, 2020 07:43
Show Gist options
  • Save AfonsoTsukamoto/7d82263f7a098a2841ac32f40baabd39 to your computer and use it in GitHub Desktop.
Save AfonsoTsukamoto/7d82263f7a098a2841ac32f40baabd39 to your computer and use it in GitHub Desktop.
Utility types for immutable js with typescript
// 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