UNPKG

2.18 kBTypeScriptView Raw
1import { IterationOf } from '../Iteration/IterationOf';
2import { Iteration } from '../Iteration/Iteration';
3import { Next } from '../Iteration/Next';
4import { Pos } from '../Iteration/Pos';
5import { At } from '../Any/At';
6import { Cast } from '../Any/Cast';
7import { NonNullable } from '../Union/NonNullable';
8import { Update } from '../List/Update';
9import { Key } from '../Iteration/Key';
10import { Key as AKey } from '../Any/Key';
11import { List } from '../List/List';
12import { Length } from '../List/Length';
13import { Extends } from '../Any/Extends';
14/**
15 * @hidden
16 */
17declare type ValidatePath<O, Path extends List<AKey>, I extends Iteration> = Update<Path, Key<I>, [
18 At<O & {}, Path[Pos<I>]>
19] extends [never] ? keyof O : Path[Pos<I>]>;
20/**
21 * @hidden
22 */
23declare type __ValidPath<O, Path extends List<AKey>, I extends Iteration = IterationOf<0>> = {
24 0: __ValidPath<NonNullable<At<O & {}, Path[Pos<I>]>>, ValidatePath<O, Path, I>, Next<I>>;
25 1: Path;
26}[Extends<Pos<I>, Length<Path>>];
27/**
28 * @hidden
29 */
30export declare type _ValidPath<O extends object, Path extends List<AKey>> = __ValidPath<O, Path> extends infer X ? Cast<X, List<AKey>> : never;
31/**
32 * Replaces invalid parts of a path with `never`
33 * @param O to be inspected
34 * @param Path to be validated
35 * @returns [[Index]][]
36 * @example
37 * ```ts
38 * import {A, L, O} from 'ts-toolbelt'
39 *
40 * // Get a property in an object `o` at any depth with `path`
41 * // `A.Cast<P, O.ValidPath<O, P>>` makes sure `path` is valid
42 * const getAt = <
43 * O extends object,
44 * P extends L.List<A.Index>
45 * >(o: O, path: A.Cast<P, O.ValidPath<O, P>>): O.Path<O, P> => {
46 * let valueAt = o
47 *
48 * for (const p of path)
49 * valueAt = valueAt[p]
50 *
51 * return valueAt as any
52 * }
53 *
54 * const test0 = getAt({a: {b: {c: 1}}}, ['a', 'b'] as const) // {c: number}
55 * const test1 = getAt({a: {b: {c: 1}}} as const, ['a', 'b'] as const) // {c: 1}
56 * const test2 = getAt({a: {b: {c: 1}}}, ['x'] as const) // error
57 * ```
58 */
59export declare type ValidPath<O extends object, Path extends List<AKey>> = O extends unknown ? Path extends unknown ? _ValidPath<O, Path> : never : never;
60export {};