Skip to content

Instantly share code, notes, and snippets.

@P4
Created June 17, 2021 16:53
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 P4/278939c76c586a7f5d7c298f09eb7980 to your computer and use it in GitHub Desktop.
Save P4/278939c76c586a7f5d7c298f09eb7980 to your computer and use it in GitHub Desktop.
Make a TypeScript type readonly, recursively
type AnyFunction = (...args: any[]) => any;
type ImmutablePrimitive = undefined | null | boolean | string | number | AnyFunction;
type Immutable<T> =
T extends ImmutablePrimitive ? T :
T extends Map<infer K, infer V> ? ReadonlyMap<Immutable<K>, Immutable<V>> :
T extends Set<infer E> ? ReadonlySet<Immutable<E>> :
{ readonly [P in keyof T]: Immutable<T[P]> }
@P4
Copy link
Author

P4 commented Jun 17, 2021

Taken from this comment, including a fix for tuples

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