Home Writing Reading

til / Remove readonly and optional parameters in TypeScript

In TypeScript we have the ability to add two mapping modifiers, readonly and ? (optional parameter), to properties and fields. When we use these, we are implicitly writing +readonly and +?, respectively. We are adding the modifier.

Similarly, we can also remove modifiers by explicitly adding a minus sign, -, in front of it, i.e., -readonly. Using this knowledge, we can create a utility that removes all modifiers from a provided type.

// Utility Type that removes:
// - Entries that are read only (-readonly)
// - Optional values (-?)
// - Nullable values (NonNullable<T>)
type RequiredMutable<T> = {
  -readonly [K in keyof T]-?: NonNullable<T[K]>;
};

// Original interface
interface Data {
  readonly name: string;
  readonly date?: Date;
  readonly age: number | null;
}

// Modified interface where all fields are mutable,
// required, and non-nullable.
type RequiredMutableData = RequiredMutable<Data>;
// {
// 	name: string,
//  date: Date,
//  age: number
// }

We could also split the utility into parts if we think that they could be useful separately.

// Remove read only modifier
type Mutable<T> = {
  -readonly [K in keyof T]: T[K];
};

// Remove optional modifier
type NoOptionals<T> = {
  [K in keyof T]-?: T[K];
};

// Remove any nullable types
type NonNull<T> = {
  [K in keyof T]: NonNullable<T[K]>;
};

// Original interface
interface Data {
  readonly name: string;
  readonly date?: Date;
  readonly age: number | null;
}

// Modified interface
type RequiredMutableNonNullData = NonNull<NoOptionals<Mutable<Data>>>;
// {
// 	name: string,
//  date: Date,
//  age: number
// }

TS Playground


Eddy Wilson. (2022-05-12). Tweet Daily Dev Tips. (2022-03-02). TypeScript and the ReadOnly option. Link


  • Loading next post...
  • Loading previous post...