Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use Partial in nested property with typescript

Tags:

typescript

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?

like image 984
dagda1 Avatar asked Dec 20 '17 21:12

dagda1


People also ask

How does partial work in TypeScript?

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.

What is partial 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.

How do I create a nested object in TypeScript?

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.

What is nested interface in TypeScript?

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.


2 Answers

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.

like image 92
CRice Avatar answered Oct 13 '22 18:10

CRice


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'         }     } } 
like image 20
Shane Avatar answered Oct 13 '22 19:10

Shane