import { type ObjectKey, parseObjectPath } from './parseObjectPath'; /** * get by path * * {@link https://github.com/developit/dlv dlv} */ export function get( obj: O, key: P | P[], def?: OrElse, ): ResolveObjectPathType { const undef = undefined; const path = parseObjectPath(key); let out: any = obj; for (const i of path) { out = out ? out[i] : undef; } return out === undef ? (def as any) : out; } /** * It tries to resolve the path of the given object, otherwise it will return OrElse * * {@link https://github.com/Pouja/typescript-deep-path-safe typescript-deep-path-safe} */ export type ResolveObjectPathType< ObjectType, Path extends string | symbol | number, OrElse, > = Path extends keyof ObjectType ? ObjectType[Path] : Path extends `${infer LeftSide}.${infer RightSide}` ? LeftSide extends keyof ObjectType ? ResolveObjectPathType : Path extends `${infer LeftSide}[${number}].${infer RightSide}` ? LeftSide extends keyof ObjectType ? ObjectType[LeftSide] extends Array ? ResolveObjectPathType : OrElse : OrElse : OrElse : Path extends `${infer LeftSide}[${number}]` ? LeftSide extends keyof ObjectType ? ObjectType[LeftSide] extends Array ? U : OrElse : OrElse : OrElse;