TypeScript Reference ยท Utility Types
TypeScript Required<T> utility type
Reference for TypeScript Required<T>: make every optional property mandatory, how the -? modifier works, and how it treats undefined and nested objects.
Required<T> builds a new object type from T in which every property is mandatory. Optional properties lose their ? marker, so a value of the new type must supply all of them. It is the mirror image of Partial<T>.
The usual use is after you have filled in defaults: the input type has optional fields, but once defaults are applied the result is guaranteed to have all of them, and Required<T> describes that result.
interface Options { retries?: number; verbose?: boolean; } type Complete = Required<Options>; // { retries: number; verbose: boolean }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
type Required<T> = { [P in keyof T]-?: T[P]; };
| Name | Description |
|---|---|
T |
An object type (interface, alias, class instance type). Its properties are copied with the same names and value types. |
Result: a mapped type with the same keys as T, all required. The -? modifier removes the optional flag from each key.
Edge cases: the -? modifier also strips the undefined that the ? itself added to the property type.
Usage notes
- Shallow only.
Required<T>changes the top level. A nested object such asconfig?: { port?: number }becomesconfig: { port?: number }; the innerportstays optional. Write a recursive mapped type if you need depth. - Strips
undefinedfrom optional properties. Withstricton,y?: numberhas the typenumber | undefinedwhen read. AfterRequired,yis plainnumber. A property that is not optional but explicitly includesundefined(y: number | undefined) is unaffected:Requiredonly touches the?marker. - Readonly is preserved. Only the optional modifier is changed. Combine with
Readonly<T>when you need both. - Does not validate at runtime. It is a compile-time promise only. Data from JSON or a network call must still be checked before you trust it.
- Does not change index signatures.
Required<Record<string, number>>is the same type as before. - Opposite:
Partial<T>makes everything optional. - Available since TypeScript 2.8.