DEV Community

Cover image for How to easily make every property in a type alias or interface to required properties in TypeScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to easily make every property in a type alias or interface to required properties in TypeScript?

Originally posted here!

To easily make every property on a type alias or interface to required properties, you can use the Required utility type and pass the type alias or interface as the first type argument to it using the angled brackets symbol (<>).

TL;DR

// a simple type
// with optional properties
type Person = {
  name?: string;
  age?: number;
};

// make all the properties in the
// `Person` type to be required
type RequiredPerson = Required<Person>;

// contents of the `RequiredPerson` type
/*
{
  name: string;
  age: number;
}
*/
Enter fullscreen mode Exit fullscreen mode

For example, let's say we have a type called Person with 2 optional properties called name having the type of string and age having the type of number like this,

// a simple type
// with optional properties
type Person = {
  name?: string;
  age?: number;
};
Enter fullscreen mode Exit fullscreen mode

Now to make all the properties in the Person type to be required we can use the Required utility type and pass the Person interface as the first type argument to it using the angled brackets symbol (<>).

It can be done like this,

// a simple type
// with optional properties
type Person = {
  name?: string;
  age?: number;
};

// make all the properties in the
// `Person` type to be required
type RequiredPerson = Required<Person>;

// contents of the `RequiredPerson` type
/*
{
  name: string;
  age: number;
}
*/
Enter fullscreen mode Exit fullscreen mode

Now if you hover over the RequiredPerson type you can see that all the properties are now required which is what we want to happen.

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.


Top comments (0)