在带有打字稿的嵌套属性中使用 Partial [英] use Partial in nested property with typescript

查看:24
本文介绍了在带有打字稿的嵌套属性中使用 Partial的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个这样的类型;

Say I have a type like this;

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

我像这样将状态设为 Partial Partial

I make state Partial like this Partial<State>

但是我怎样才能使嵌套的属性部分化,例如,如果我想让 two 也部分化.

But how can I make on of the nested properties partial, for example if I wanted to make two also partial.

我该怎么做?

推荐答案

你可以很容易地定义你自己的 RecursivePartial 类型,这将使​​所有属性,包括嵌套的,都是可选的:

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]>;
};

如果您只希望您的某些属性是部分属性,那么您可以将其与交集和 Pick 一起使用:

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>;

这将使除了所有在K参数中指定的键都是可选的.

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

这篇关于在带有打字稿的嵌套属性中使用 Partial的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆