Skip to main content

get

A function that returns the value at a specified path in a given object in a type-safe manner. You can access deeply nested properties using dot notation.


Code

🔗 View source code


Interface

typescript
function get<T extends Record<PropertyKey, any>, K extends PropertyPath<T>>(
obj: T,
path: K,
defaultValue?: GetByPath<T, K>
): GetByPath<T, K>;

Usage

Basic Usage

typescript
import { get } from '@modern-kit/utils';

const obj: { a: { b: { c: number } } } = { a: { b: { c: 1 } } };

// Single property access
get(obj, 'a'); // { b: { c: 1 } }

// Nested property access
get(obj, 'a.b'); // { c: 1 }
get(obj, 'a.b.c'); // 1

Optional Property Access

typescript
const obj: { a: { b?: { c: number } } } = { a: { b: { c: 1 } } };

// Optional property access
get(obj, 'a.b');
// value: { c: 1 }
// type: { c: 1 } | undefined

get(obj, 'a.b?.c');
// value: 1
// type: 1 | undefined

Default Value

typescript
const obj: { a?: { b?: { c?: number } } } = {};

get(obj, 'a', { b: { c: 1 } }); // { b: { c: 1 } }
get(obj, 'a?.b', { c: 1 }); // { c: 1 }
get(obj, 'a?.b?.c', 1); // 1