type-fest
type-fest copied to clipboard
Proposal: `RecordOf`
Short summary
Given:
-
TupleType
: a tuple of similar objects -
KeyProperty
: a key that is...- Present on every object in the tuple
- Used to hold
string
values
Provide:
A Record
-like object that indexes the tuple entries using the specified key property instead of array indexes.
Potential definition
Type:
type RecordOf<
TupleType extends Array<object> | ReadonlyArray<object>,
KeyProperty extends keyof TupleType[number]
> = {
[Item in TupleType[number] as `${Item[KeyProperty]}`]: Item;
};
Transformation function:
function toRecord<
TupleType extends Array<object> | ReadonlyArray<object>,
KeyProperty extends keyof TupleType[number]
>(
tuple: TupleType,
keyProperty: KeyProperty
): RecordOf<TupleType, KeyProperty> {
return Object.fromEntries(
tuple.map((item: TupleType[number]) => [String(item[keyProperty]), item])
) as RecordOf<TupleType, KeyProperty>;
}
Example usage
const animalList = [
{ name: 'Shadow', species: 'dog', breed: 'Golden Retriever' },
{ name: 'Chance', species: 'dog', breed: 'Bulldog' },
{ name: 'Sassy', species: 'cat', breed: 'Siamese' },
{ name: 'Jake the Dog', species: 'dog', breed: 'Bulldog', isMagical: true },
] as const;
const animals = toRecord(animalList, 'name');
console.log(animals.Shadow);
console.log(animals['Jake the Dog'].isMagical);
Other potential variations
- Provide transformation options (like camel casing the keys or adding a prefix)
Upvote & Fund
- We're using Polar.sh so you can upvote and help fund this issue.
- The funding will be given to active contributors.
- Thank you in advance for helping prioritize & fund our backlog.