UNPKG

1.83 kBTypeScriptView Raw
1import {Primitive} from './basic';
2
3/**
4Convert `object`s, `Map`s, `Set`s, and `Array`s and all of their keys/elements into immutable structures recursively.
5
6This 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
8Please 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
18import {ReadonlyDeep} from 'type-fest';
19import dataJson = require('./data.json');
20
21const data: ReadonlyDeep<typeof dataJson> = dataJson;
22
23export default data;
24
25// test.ts
26import data from './main';
27
28data.foo.push('bar');
29//=> error TS2339: Property 'push' does not exist on type 'readonly string[]'
30```
31*/
32export 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/**
43Same as `ReadonlyDeep`, but accepts only `ReadonlyMap`s as inputs. Internal helper for `ReadonlyDeep`.
44*/
45interface ReadonlyMapDeep<KeyType, ValueType>
46 extends ReadonlyMap<ReadonlyDeep<KeyType>, ReadonlyDeep<ValueType>> {}
47
48/**
49Same as `ReadonlyDeep`, but accepts only `ReadonlySet`s as inputs. Internal helper for `ReadonlyDeep`.
50*/
51interface ReadonlySetDeep<ItemType>
52 extends ReadonlySet<ReadonlyDeep<ItemType>> {}
53
54/**
55Same as `ReadonlyDeep`, but accepts only `object`s as inputs. Internal helper for `ReadonlyDeep`.
56*/
57type ReadonlyObjectDeep<ObjectType extends object> = {
58 readonly [KeyType in keyof ObjectType]: ReadonlyDeep<ObjectType[KeyType]>
59};
60
\No newline at end of file