Open History to see the last commit
1import { describe, expectTypeOf, it } from 'vitest'
2β
3// types
4import type { CollapsiblePaths } from '../src/utils/deep-keys'
5β
6type WithDeeplyNestedObject = {
7 a: {
8 b: {
9 c: {
10 d: {
11 e: {
12 f: {
13 g: {
14 h: {
15 i: {
16 j: number
17 }
18 }
19 }
20 }
21 }
22 }
23 }
24 }
25 }
26}
27β
28type _DeeplyNestedObject = CollapsiblePaths<WithDeeplyNestedObject>
29β
30type WithAny = {
31 errors?: any
32}
33β
34type _Any = CollapsiblePaths<WithAny>
35β
36type ArrayRecursion = { arr: Array<Array<Array<Array<[]>>>> }
37β
38type _ArrayRecursion = CollapsiblePaths<ArrayRecursion>
39β
40type WithUndefined = {
41 status?: {
42 valid: boolean
43 error?: {
44 message: string
45 }
46 }
47}
48β
49type _WithUndefined = CollapsiblePaths<WithUndefined>
50β
51type WithUnknown = {
52 payload: unknown
53}
54β
55type _WithUnknown = CollapsiblePaths<WithUnknown>
56β
57type WithRealisticState = {
58 canSubmit?: boolean
59 isSubmitting?: boolean
60 errors?: Array<any>
61 errorMap?: Record<string, any>
62}
63β
64type _WithRealisticState = CollapsiblePaths<WithRealisticState>
65β
66type WithGeneric<TData> = {
67 generic: TData
68}
69β
70type _WithGeneric = CollapsiblePaths<WithGeneric<{ a: { b: string } }>>
71β
72describe('deep-keys', () => {
73 it('should type deeply nested keys', () => {
74 expectTypeOf<_DeeplyNestedObject>().toEqualTypeOf<
75 | ''
76 | 'a'
77 | 'a.b'
78 | 'a.b.c'
79 | 'a.b.c.d'
80 | 'a.b.c.d.e'
81 | 'a.b.c.d.e.f'
82 | 'a.b.c.d.e.f.g'
83 | 'a.b.c.d.e.f.g.h'
84 | 'a.b.c.d.e.f.g.h.i'
85 >()
86 })
87β
88 it('should handle any', () => {
89 expectTypeOf<_Any>().toEqualTypeOf<'' | 'errors'>()
90 })
91β
92 it('should handle array recursion', () => {
93 expectTypeOf<_ArrayRecursion>().toEqualTypeOf<
94 | ''
95 | 'arr'
96 | `arr[${number}]`
97 | `arr[${number}][${number}]`
98 | `arr[${number}][${number}][${number}]`
99 | `arr[${number}][${number}][${number}][${number}]`
100 >()
101 })
102β
103 it('should handle undefined', () => {
104 expectTypeOf<_WithUndefined>().toEqualTypeOf<
105 '' | 'status' | 'status.error'
106 >()
107 })
108β
109 it('should handle unknown', () => {
110 expectTypeOf<_WithUnknown>().toEqualTypeOf<''>()
111 })
112β
113 it('should handle realistic state', () => {
114 expectTypeOf<_WithRealisticState>().toEqualTypeOf<
115 '' | 'errors' | 'errorMap' | `errors[${number}]` | `errorMap.${string}`
116 >()
117 })
118β
119 it('should handle generics', () => {
120 expectTypeOf<_WithGeneric>().toEqualTypeOf<'' | 'generic' | 'generic.a'>()
121 })
122})