Imagine
type Individual = {
name: string;
age: number;
};
const john = {
name: "John",
age: 28,
} as const;
const emily = {
name: "Emily",
age: 35,
} as const;
I am looking to create a function that takes an individual and transforms it into an object with the name of the person as the key and the person object as the value.
If I am working with one individual, I can achieve this by using
function getIndividual<T extends Individual>(individualOption: T) {
let person = {} as Record<(typeof individualOption)["name"], typeof individualOption>;
return person;
}
const individual = getIndividual(john); // John: {name: "John", age: 28}
const individualName = individual.John.name; // John
However, when attempting to extend this functionality to accept an array of individuals, the specific types are not correctly identified for each index.
function getIndividuals<T extends Individual>(individualsOptions: T[]) {
let individuals = {} as Record<
(typeof individualsOptions)[number]["name"],
(typeof individualsOptions)[number]
>;
return individuals;
}
const individuals = getIndividuals([john, emily]);
const johnName = individuals.John.name; // John | Emily
const emilyName = individuals.Emily.name; // John | Emily
Is there a way to modify this code so that johnName
returns "John" and emilyName
returns "Emily" instead of a combination of both?