Making the Properties of an Object Optional in Typescript

Kayode Oluwasegun
1 min readDec 3, 2022

--

Photo by Fotis Fotopoulos on Unsplash

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>'

--

--

Kayode Oluwasegun
Kayode Oluwasegun

Written by Kayode Oluwasegun

I enjoy reading and writing interesting stories with a keen interest in web technologies, backend development, personal growth, motivation and development.

No responses yet