Galdor
Galdor

Reputation: 1985

create typescript interface with readonly fields similar to one without readonly fields

I have two interfaces:

Interface readwrite {
  f1: string;
  f2: boolean;
}

Interface readonlyint {
  readonly f1: string;
  readonly f2: boolean;
}

Sometimes I want that the fields cannot be changed, so I created the readonlyint interface. I there a possibility to derive readonlyint from readwrite? I don't want to copy all fields, the field-list can be much longer.

Upvotes: 1

Views: 98

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68675

There is a Readonly<T> type, which you can use. It is doing the same.

interface ReadWrite {
   f1: string;
   f2: boolean;
}

type ReadonlyReadWrite = Readonly<ReadWrite>;

The shape of the ReadonlyReadWrite will be

interface ReadonlyReadWrite {
   readonly f1: string;
   readonly f2: boolean;
}

Upvotes: 2

Related Questions