Search code examples
typescriptreadonlyreadonly-attribute

Typescript: extending an interface and redeclaring the existing fields as readonly


Let's say we have an interface like this:

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

I want to call Readonly and create a readonly version of the interface, e.g.

interface PersonReadonly extends Readonly<Person> {}

which will be equivalent to writing

interface PersonReadonly {
  readonly name: string;
  readonly age: number;
}

Can we write such a Readonly generic interface, or is it written already?


Solution

  • You can do:

    type PersonReadonly = Readonly<Person>
    

    But it is not an interface. For example, you can't add a new member somewhere else.

    Edit from May, 2017: Since TS 2.2 (February, 2017), interfaces can be derived from types.