Skip to main content

propertyOf()

propertyOf<T>(object): <Key>(key) => T[Key]

Creates a function that returns the value at the given key of object.

DEPRECATED

Use an inline arrow function (key) => obj[key] instead.


Type Parametersโ€‹

T: T extends objectโ€‹

The type of the object.


Parametersโ€‹

object: Tโ€‹

The object to query.


Returns: <Key>(key): T[Key]โ€‹

A function that returns the property value for a given key.


Sinceโ€‹

2.0.0


Also known asโ€‹

propertyOf (Lodash, es-toolkit) ยท โŒ (Remeda, Radashi, Ramda, Effect, Modern Dash, Antfu)


Exampleโ€‹

// โŒ Deprecated approach
const getValue = propertyOf({ a: 1, b: 2 });
getValue('a'); // => 1
getValue('b'); // => 2

// โœ… Recommended approach
const obj = { a: 1, b: 2 };
const getValue = (key: 'a' | 'b') => obj[key];
getValue('a'); // => 1
getValue('b'); // => 2

How it works?โ€‹

Creates a function that returns the value at path of object. Deprecated: Use an arrow function.

Native Equivalentโ€‹

// โŒ propertyOf(obj)
// โœ… key => obj[key]

Use Casesโ€‹

Create property getter ๐Ÿ“Œโ€‹

Create function to get property from fixed object.

const obj = { a: 1, b: 2, c: 3 };
const getValue = (key: keyof typeof obj) => obj[key];
getValue('a'); // 1
getValue('b'); // 2

Map keys to valuesโ€‹

Convert array of keys to values.

const config = { host: 'localhost', port: 3000 };
const keys = ['host', 'port'] as const;
const values = keys.map(k => config[k]);
// ['localhost', 3000]