1
const persons = [
  {
    name: "John",
    age: 80,
  },
  {
    name: "Julia",
    age: 78,
  },
] as const;

function makePersonsByName(people: typeof persons): {
  [key in typeof persons[number]["name"]]: typeof persons[number];
} {
  let object = {};

  for (let person of persons) {
    object = object
      ? {
          ...object,
          [person.name]: person,
        }
      : {
          [person.name]: person,
        };
  }
  return object;
}

the above code is giving me this error

Type '{}' is missing the following properties from type '{ John: { readonly name: "John"; readonly age: 80; } | { readonly name: "Julia"; readonly age: 78; }; Julia: { readonly name: "John"; readonly age: 80; } | { readonly name: "Julia"; readonly age: 78; }; }': John, Julia

what is the best way to fix this

1 Answer 1

2
const persons = [
    {
        name: "John",
        age: 80,
    },
    {
        name: "Julia",
        age: 78,
    },
] as const;

type PersonName = typeof persons[number]["name"];
type Person = typeof persons[number];
// optional to allow empty object to be assignable to this type
type NewlyMappedPerson = {
    [key in PersonName]?: Person;
};

function makePersonsByName(people: typeof persons): NewlyMappedPerson {
    let object: NewlyMappedPerson = {};
    // use reduce to iterate over array and add to the object
    return persons.reduce((acc, person) => {
        return { ...acc, [person.name]: person };
    }, object);
}

console.log(makePersonsByName(persons));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.