Type Alias Get<BaseType, Path, Options>

Get: GetWithPath<BaseType, Path extends string ? ToPath<Path> : Path, Options>

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.

Type Parameters

  • BaseType
  • Path extends string | readonly string[]
  • Options extends GetOptions = {}
import type {Get} from 'type-fest';
import * as 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}> | undefined

// 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}> | undefined

// Non-strict mode:
Get<string[], '3', {strict: false}> //=> string
Get<Record<string, string>, 'foo', {strict: true}> // => string