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.
1// Utility Type that removes:
2// - Entries that are read only (-readonly)
3// - Optional values (-?)
4// - Nullable values (NonNullable<T>)
5type RequiredMutable<T> = {
6 -readonly [K in keyof T]-?: NonNullable<T[K]>
7}
8
9// Original interface
10interface Data {
11 readonly name: string
12 readonly date?: Date
13 readonly age: number | null
14}
15
16// Modified interface where all fields are mutable,
17// required, and non-nullable.
18type RequiredMutableData = RequiredMutable<Data>
19// {
20// name: string,
21// date: Date,
22// age: number
23// }
We could also split the utility into parts if we think that they could be useful separately.
1// Remove read only modifier
2type Mutable<T> = {
3 -readonly [K in keyof T]: T[K];
4};
5
6// Remove optional modifier
7type NoOptionals<T> = {
8 [K in keyof T]-?: T[K];
9};
10
11// Remove any nullable types
12type NonNull<T> = {
13 [K in keyof T]: NonNullable<T[K]>;
14};
15
16// Original interface
17interface Data {
18 readonly name: string;
19 readonly date?: Date;
20 readonly age: number | null;
21}
22
23// Modified interface
24type RequiredMutableNonNullData = NonNull<NoOptionals<Mutable<Data>>>;
25// {
26// name: string,
27// date: Date,
28// age: number
29// }
Eddy Wilson. (2022-05-12). Tweet Daily Dev Tips. (2022-03-02). TypeScript and the ReadOnly option. Link