Making the Properties of an Object Optional in Typescript

Making the Properties of an Object Optional in Typescript

In cases where you want to construct a type with all properties of another type set to optional, the Partial<Type> is a helpful utility.

This is pretty useful when you need the subset of a given type.

For instance,

interface Person {
  name: string;
  age: number;
}

let persons: Person[] = [
  { name: "Abel", age: 19 },
  { name: "Drake", age: 23 },
  { name: "Lucid", age: 22 },
  { name: "Mark", age: 87 },
];

// takes an argument of 
function searchBySub(subObj: Partial<Person>) {
  return persons.find((person) => {
    return Object.keys(subObj).every((key) => {
      return person[key] === subObj[key];
    });
  });
}

The argument, subOj, can only be a sub-type of Person, so the code below would raise a type error

searchBySub({ unknownProperty: "unknown" }) 
// error - Argument of type '{ unknownProperty: string }' is not
// assignable to parameter of type 'Partial<Person>'