Skip to main content
Module

x/scaffold/src/deps/types.ts>Get

scaffold your next project with style and 💗
Latest
type alias Get
import { type Get } from "https://deno.land/x/scaffold@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

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

Type Parameters

BaseType
Path extends string | readonly string[]
optional
Options extends GetOptions = { }
definition: GetWithPath<BaseType, Path extends string ? ToPath<Path> : Path, Options>