Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 484
Yavuz Mester Avatar asked Jan 04 '23 22:01

Yavuz Mester


1 Answers

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.

like image 190
Paleo Avatar answered Jan 13 '23 09:01

Paleo