Utility, Mapped and Indexed Types
Utility types are small mapped and conditional types from the standard library. Know exactly how each is defined, because their edge cases come straight from those definitions.
Key points
- 1
keyof Tlists property keys;T[K]reads property types;T[keyof T]is the union of value types, andT[number]is an array or tuple element type. - 2
keyof (A | B)is the shared keys only, whilekeyof (A & B)is every key. A string index signature makeskeyofstring | number. - 3
Homomorphic mapped types (
{ [K in keyof T]: … }) copy?andreadonly, distribute over unions, and map arrays and tuples to arrays and tuples. - 4
Change modifiers with
+/-:-readonlymakes properties writable,-?makes them required and strips theundefinedthat came from?. - 5
Key remapping with
ascan rename keys and filter them out by remapping tonever. - 6
Omit<T, K>isPick<T, Exclude<keyof T, K>>: it accepts any key and is not distributive, so it collapses unions. Write a distributive helper when you need one. - 7
ReturnTypeandParametersread the last overload;Awaitedunwraps thenables recursively and distributes over unions.
Common traps
ReadonlyandPartialare shallow, and naive deep versions break functions (they lose call signatures) and arrays (elements gainundefined).Omiton a type with a string index signature drops every named property.A typo in
Omit<T, "nmae">compiles silently, whilePickwould reject it.
Read the source
Test yourself on Utility, Mapped and Indexed Types
Ten questions, with the answer and explanation after each one.