You need a version of your object type where all the properties are optional but don’t want to write a duplicate type and maintain both copies
- Use the
Partial<Type>
utility type - TS docs: “Constructs a type with all properties of
Type
set to optional. This utility will return a type that represents all subsets of a given type.”
Create a new type that’s defined as your original type wrapped in Partial<>
:
type Original = {
foo: string
}
type Optional = Partial<Original>
That’s it. 🙂
Now, when you use the Optional
type, you’ll see that property foo
is now string | undefined
instead of string
:
// add usage example
Partial<Type>
| TypeScript docs- Make all properties optional in TypeScript | Borislav Hadzhiev
- Make all properties within a Typescript interface optional | StackOverflow
- Optional Properties | TypeScript docs