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

May 12, 2022 - 2 min read

To easily make every property on a type alias or interface to readonly properties, you can use the Readonly 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
type Person = {
  name: string;
  age: number;
};

// make all the properties in the
// `Person` type to be readonly
type ReadonlyPerson = Readonly<Person>;

// contents of the `ReadonlyPerson` type
/*
{
  readonly name: string;
  readonly age: number;
}
*/

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

// a simple type
type Person = {
  name: string;
  age: number;
};

Now to make all the properties in the Person type to be readonly we can use the Readonly 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
type Person = {
  name: string;
  age: number;
};

// make all the properties in the
// `Person` type to be readonly
type ReadonlyPerson = Readonly<Person>;

// contents of the `ReadonlyPerson` type
/*
{
  readonly name: string;
  readonly age: number;
}
*/

Now if you hover over the ReadonlyPerson type you can see that all the properties are now readonly 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 😃.