1 | import {Primitive} from './basic';
|
---|
2 |
|
---|
3 | /**
|
---|
4 | Convert `object`s, `Map`s, `Set`s, and `Array`s and all of their keys/elements into immutable structures recursively.
|
---|
5 |
|
---|
6 | This is useful when a deeply nested structure needs to be exposed as completely immutable, for example, an imported JSON module or when receiving an API response that is passed around.
|
---|
7 |
|
---|
8 | Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/13923) if you want to have this type as a built-in in TypeScript.
|
---|
9 |
|
---|
10 | @example
|
---|
11 | ```
|
---|
12 | // data.json
|
---|
13 | {
|
---|
14 | "foo": ["bar"]
|
---|
15 | }
|
---|
16 |
|
---|
17 | // main.ts
|
---|
18 | import {ReadonlyDeep} from 'type-fest';
|
---|
19 | import dataJson = require('./data.json');
|
---|
20 |
|
---|
21 | const data: ReadonlyDeep<typeof dataJson> = dataJson;
|
---|
22 |
|
---|
23 | export default data;
|
---|
24 |
|
---|
25 | // test.ts
|
---|
26 | import data from './main';
|
---|
27 |
|
---|
28 | data.foo.push('bar');
|
---|
29 | //=> error TS2339: Property 'push' does not exist on type 'readonly string[]'
|
---|
30 | ```
|
---|
31 | */
|
---|
32 | export type ReadonlyDeep<T> = T extends Primitive | ((...arguments: any[]) => unknown)
|
---|
33 | ? T
|
---|
34 | : T extends ReadonlyMap<infer KeyType, infer ValueType>
|
---|
35 | ? ReadonlyMapDeep<KeyType, ValueType>
|
---|
36 | : T extends ReadonlySet<infer ItemType>
|
---|
37 | ? ReadonlySetDeep<ItemType>
|
---|
38 | : T extends object
|
---|
39 | ? ReadonlyObjectDeep<T>
|
---|
40 | : unknown;
|
---|
41 |
|
---|
42 | /**
|
---|
43 | Same as `ReadonlyDeep`, but accepts only `ReadonlyMap`s as inputs. Internal helper for `ReadonlyDeep`.
|
---|
44 | */
|
---|
45 | interface ReadonlyMapDeep<KeyType, ValueType>
|
---|
46 | extends ReadonlyMap<ReadonlyDeep<KeyType>, ReadonlyDeep<ValueType>> {}
|
---|
47 |
|
---|
48 | /**
|
---|
49 | Same as `ReadonlyDeep`, but accepts only `ReadonlySet`s as inputs. Internal helper for `ReadonlyDeep`.
|
---|
50 | */
|
---|
51 | interface ReadonlySetDeep<ItemType>
|
---|
52 | extends ReadonlySet<ReadonlyDeep<ItemType>> {}
|
---|
53 |
|
---|
54 | /**
|
---|
55 | Same as `ReadonlyDeep`, but accepts only `object`s as inputs. Internal helper for `ReadonlyDeep`.
|
---|
56 | */
|
---|
57 | type ReadonlyObjectDeep<ObjectType extends object> = {
|
---|
58 | readonly [KeyType in keyof ObjectType]: ReadonlyDeep<ObjectType[KeyType]>
|
---|
59 | };
|
---|