Skip to content
Source
Sign inSign up
TanStack/devtools
Open History to see the last commit

deep-keys.ts

122 lines2.5 KB

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 }
27​
28type _DeeplyNestedObject = CollapsiblePaths<WithDeeplyNestedObject>
29​
30type WithAny = {
31 errors?: any
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 }
48​
49type _WithUndefined = CollapsiblePaths<WithUndefined>
50​
51type WithUnknown = {
52 payload: unknown
54​
55type _WithUnknown = CollapsiblePaths<WithUnknown>
56​
57type WithRealisticState = {
58 canSubmit?: boolean
59 isSubmitting?: boolean
60 errors?: Array<any>
61 errorMap?: Record<string, any>
63​
64type _WithRealisticState = CollapsiblePaths<WithRealisticState>
65​
66type WithGeneric<TData> = {
67 generic: TData
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})