Aller au contenu principal

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]