Skip to content

Instantly share code, notes, and snippets.

@arv
Last active November 17, 2022 08:43
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 arv/f5f060d8b5da16fda7476b13bf8172e0 to your computer and use it in GitHub Desktop.
Save arv/f5f060d8b5da16fda7476b13bf8172e0 to your computer and use it in GitHub Desktop.
A simple TypeScript Immutable type
import type {Immutable} from './immutable.js';
type Todo = {
id: string;
done: boolean;
order: string;
text: string;
};
type ImmutableTodo = Immutable<Todo>;
type Primitive = undefined | null | boolean | string | number | symbol | bigint;
/**
* Create a deeply immutable type from a type that may contain mutable types.
*/
export type Immutable<T> = T extends Primitive
? T
: T extends Array<infer U>
? ImmutableArray<U>
: ImmutableObject<T>;
// This does not deal with Maps or Sets (or Date or RegExp or ...).
export type ImmutableArray<T> = ReadonlyArray<Immutable<T>>;
export type ImmutableObject<T> = { readonly [K in keyof T]: Immutable<T[K]> };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment