Say I have a type like this;
interface State { one: string, two: { three: { four: string }, five: string } }
I make state Partial like this Partial<State>
But how can I make on of the nested properties partial, for example if I wanted to make two
also partial.
How would I do this?
The Partial type in TypeScript is a utility type which does the opposite of Required. It sets all properties in a type to optional. Let's look at how it works. If you're interested in the opposite problem, try my article on how the Required type works in TypeScript.
Partial<Type>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.
Use an interface or a type alias to type a nested object in TypeScript. You can set properties on the interface that point to nested objects. The type of the object can have as deeply nested properties as necessary.
TypeScript Nested Interface TypeScript allows both type aliases and interface to be nested. An object typed with a nested interface should have all its properties structured the same way as the interface definition.
You can pretty easily define your own RecursivePartial
type, which will make all properties, included nested ones, optional:
type RecursivePartial<T> = { [P in keyof T]?: RecursivePartial<T[P]>; };
If you only want some of your properties to be partial, then you can use this with an intersection and Pick
:
type PartialExcept<T, K extends keyof T> = RecursivePartial<T> & Pick<T, K>;
That would make everything optional except for the keys specified in the K
parameter.
This is possible, you can create a 'deep' partial type as followed:
type DeepPartial<T> = { [P in keyof T]?: DeepPartial<T[P]>; };
Which can be used as followed
const state: DeepPartial<State> = { two: { three: { four: '4' } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With