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]