1

I have an interface that is derived from a validation library's schema definition. Some of the values in the definition are readonly since they are the server's responsibility to set. When I am constructing values to send to the server, however, I want to reuse the interface as much as possible. Ideally, I would be able to write a type like:

type StripReadonly<T> = // ???;

// And use it like
interface IFoo {
  a: number;
  readonly b: string;
}

type Derived = StripReadonly<T>; // { a: number; }

I am using a builder pattern to construct values to post to the server so it would be nice to only allow setting the mutable values in the internal partial representation I'm building up to avoid the class of errors, where I post a value for a readonly field, at compile time.

I can't seem to find a good way to do this. TypeScript does have a way to subtract the readonly property from an interface (to derive Writable or Mutable on an interface) but there doesn't seem to be a way to filter out / to Exclude those values.

Souperman
  • 5,057
  • 1
  • 14
  • 39

1 Answers1

0

There is syntax to remove the readonly property on a type. Filtering the readonly types is a bit trickier. I'm not familiar with a way to do that.

type Writeable<T> = { -readonly [P in keyof T]: T[P] };
type MutableRequired<T> = { -readonly [P in keyof T]-?: T[P] }; // Remove readonly and ?

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html

Hath995
  • 821
  • 6
  • 12