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]