import { type Get } from "https://deno.land/x/actionify@0.3.0/src/deps/types.ts";
Get a deeply-nested property from an object using a key path, like Lodash's .get()
function.
Use-case: Retrieve a property from deep inside an API response or some other complex object.
Examples
Example 1
Example 1
import type {Get} from 'type-fest';
importas lodash from 'lodash';
const get = <BaseType, Path extends string | readonly string[]>(object: BaseType, path: Path): Get<BaseType, Path> =>
lodash.get(object, path);
interface ApiResponse {
hits: {
hits: Array<{
_id: string
_source: {
name: Array<{
given: string[]
family: string
}>
birthDate: string
}
}>
}
}
const getName = (apiResponse: ApiResponse) =>
get(apiResponse, 'hits.hits[0]._source.name');
//=> Array<{given: string[]; family: string}>
// Path also supports a readonly array of strings
const getNameWithPathArray = (apiResponse: ApiResponse) =>
get(apiResponse, ['hits','hits', '0', '_source', 'name'] as const);
//=> Array<{given: string[]; family: string}>
// Strict mode:
Get<string[], '3', {strict: true}> //=> string | undefined
Get<Record<string, string>, 'foo', {strict: true}> // => string | undefined