UNPKG

2.21 kBTypeScriptView Raw
1import { Key } from '../Any/Key';
2import { Head } from '../List/Head';
3import { List } from '../List/List';
4import { Pop } from '../List/Pop';
5import { Tail } from '../List/Tail';
6import { Path } from '../Object/Path';
7import { UnionOf } from '../Object/UnionOf';
8import { Select } from '../Union/Select';
9import { Join } from '../String/Join';
10import { Split } from '../String/Split';
11/**
12 * @ignore
13 */
14declare type Index = number | string;
15/**
16 * @ignore
17 */
18declare type KeyToIndex<K extends Key, SP extends List<Index>> = number extends K ? Head<SP> : K & Index;
19/**
20 * @ignore
21 */
22declare type MetaPath<O, D extends string, SP extends List<Index> = [], P extends List<Index> = []> = {
23 [K in keyof O]: MetaPath<O[K], D, Tail<SP>, [...P, KeyToIndex<K, SP>]> | Join<[...P, KeyToIndex<K, SP>], D>;
24};
25/**
26 * @ignore
27 */
28declare type NextPath<OP> = Select<UnionOf<Exclude<OP, string> & {}>, string>;
29/**
30 * @ignore
31 */
32declare type ExecPath<A, SP extends List<Index>, Delimiter extends string> = NextPath<Path<MetaPath<A, Delimiter, SP>, SP>>;
33/**
34 * @ignore
35 */
36declare type HintPath<A, P extends string, SP extends List<Index>, Exec extends string, D extends string> = [Exec] extends [never] ? ExecPath<A, Pop<SP>, D> : Exec | P;
37/**
38 * @ignore
39 */
40declare type _AutoPath<A, P extends string, D extends string, SP extends List<Index> = Split<P, D>> = HintPath<A, P, SP, ExecPath<A, SP, D>, D>;
41/**
42 * Auto-complete, validate, and query the string path of an object `O`
43 * @param O to work on
44 * @param P path of `O`
45 * @param D (?=`'.'`) delimiter for path
46 *
47 * ```ts
48 * declare function get<O extends object, P extends string>(
49 * object: O, path: AutoPath<O, P>
50 * ): Path<O, Split<P, '.'>>
51 *
52 * declare const user: User
53 *
54 * type User = {
55 * name: string
56 * friends: User[]
57 * }
58 *
59 * // works
60 * const friendName = get(user, 'friends.40.name')
61 * const friendFriendName = get(user, 'friends.40.friends.12.name')
62 *
63 * // errors
64 * const friendNames = get(user, 'friends.40.names')
65 * const friendFriendNames = get(user, 'friends.40.friends.12.names')
66 * ```
67 */
68export declare type AutoPath<O extends any, P extends string, D extends string = '.'> = _AutoPath<O, P, D>;
69export {};