use Partial in nested property with typescript

前端 未结 4 978
慢半拍i
慢半拍i 2020-12-13 13:13

Say I have a type like this;

interface State {
  one: string,
  two: {
    three: {
      four: string
    },
    five: string
  }
}

I make

4条回答
  •  佛祖请我去吃肉
    2020-12-13 13:40

    You can pretty easily define your own RecursivePartial type, which will make all properties, included nested ones, optional:

    type RecursivePartial = {
        [P in keyof T]?: RecursivePartial;
    };
    

    If you only want some of your properties to be partial, then you can use this with an intersection and Pick:

    type PartialExcept = RecursivePartial & Pick;
    

    That would make everything optional except for the keys specified in the K parameter.

提交回复
热议问题