DEV Community

Cover image for Making the Properties of an Object Optional in Typescript
Kayode
Kayode

Posted on • Originally published at blog.zt4ff.dev

4 3

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];
    });
  });
}
Enter fullscreen mode Exit fullscreen mode

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>' 
Enter fullscreen mode Exit fullscreen mode

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay