Skip to content

Instantly share code, notes, and snippets.

@karlvr
Last active June 27, 2018 04:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karlvr/d2db29ed16ad196eba454fd5c8ab1ec0 to your computer and use it in GitHub Desktop.
Save karlvr/d2db29ed16ad196eba454fd5c8ab1ec0 to your computer and use it in GitHub Desktop.
Immutable-js Typescript 2.8 attempt
import { Map, fromJS } from 'immutable'
function toImmutable<T>(array: T[]): ImmutableList<T>
function toImmutable<T extends object>(obj: T): ImmutableObject<T>
function toImmutable<T>(value: T): ImmutableObject<T> | ImmutableList<T> {
return fromJS(value)
}
type Diff<T, U> = T extends U ? never : T
type ImmutableObjectValues<T> = {
[P in keyof T]:
undefined extends T[P] ? (
Diff<T[P], undefined> extends object ? undefined | ImmutableObject<Diff<T[P], undefined>> :
T[P]
) :
T[P] extends any[] ? ImmutableList<T[P][number]> :
T[P] extends object ? ImmutableObject<T[P]> : T[P]
}
interface ImmutableObject<T> {
get<P extends keyof T>(key: P): ImmutableObjectValues<T>[P]
set<P extends keyof T>(key: P, value: ImmutableObjectValues<T>[P]): ImmutableObject<T>
toObject(): T
}
function ImmutableList<T>(list: T): ImmutableList<T> {
return fromJS(list)
}
interface ImmutableList<T> {
count(): number
get(index: number): T extends object ? ImmutableObject<T> : T
toArray(): [T]
}
@karlvr
Copy link
Author

karlvr commented Jun 27, 2018

The big problem is that it doesn't currently support nested sets or any nested operations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment