Last active
November 17, 2022 08:43
-
-
Save arv/f5f060d8b5da16fda7476b13bf8172e0 to your computer and use it in GitHub Desktop.
A simple TypeScript Immutable type
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 type {Immutable} from './immutable.js'; | |
type Todo = { | |
id: string; | |
done: boolean; | |
order: string; | |
text: string; | |
}; | |
type ImmutableTodo = Immutable<Todo>; |
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
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