Learning TypeScript 2.x
上QQ阅读APP看书,第一时间看更新

Mapped type modifiers

TypeScript 2.8 introduced a few operators that allow us to have a greater level of control over the definition of mapped types:

  • We can use the readonly modifier to flag a property as immutable.
  • We can use the ? operator to flag a property as optional.
  • We can use the + operator to apply a modifier, such as the readonly modifier, to a property in a type. We can also use the + operator with the ? operator.
  • We can use the - operator to apply a modifier, such as the readonly modifier to a property in a type. We can also use the + operator with the ? operator.

We will now examine a few examples. The code snippet declares a mapped type that can be used to transform a type, T, into a new type that contains all the properties in T but is marked as both readonly and optional:

type ReadonlyAndPartial1<T> = {
readonly [P in keyof T]?: T[P]
}

The following type declaration is identical to the one in the preceding code snippet:

type ReadonlyAndPartial2<T> = {
+readonly [P in keyof T]+?: T[P];
}

The following type can be used to remove the readonly modifier from all the properties in a given type T:

type Mutable<T> = {
-readonly [P in keyof T]: T[P]
}

We can apply the Mutable type to the following interface to generate a new type. The abc property is no longer immutable, but the def property is still optional:

interface Foo {
readonly abc: number;
def?: string;
}

type TotallyMutableFoo = Mutable<Foo>

Finally, the following code snippet declares a mapped type that can be used to remove the optional properties in a given type T:

type Required<T> = {
[P in keyof T]-?: T[P];
}