TypeScript:深偏? [英] TypeScript: deep partial?

查看:30
本文介绍了TypeScript:深偏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 TypeScript 中指定一个部分类型,同时让所有子对象也成为部分对象?例如:

Is there a way to specify a partial type in TypeScript that also makes all child objects partials as well? For example:

interface Foobar {
  foo: number;
  bar: {
    baz: boolean;
    qux: string;
  };
}

const foobar: Partial<Foobar> = {
  foo: 1,
  bar: { baz: true }
};

这会引发以下错误:

TS2741:类型 '{ baz: true; 中缺少属性 'qux'.}' 但需要在类型 '{ baz: boolean;qux:字符串;}'.

有什么办法可以让子节点也部分化吗?

Is there any way to make child nodes partials as well?

推荐答案

如果您正在寻找快速简便的解决方案,请查看 type-fest 包,其中包含许多有用的预构建 TypeScript 类型,包括 PartialDeep 类型.

If you're looking for a quick and easy solution, check out the type-fest package, which has many useful prebuilt TypeScript types including the PartialDeep type.

有关更具技术性和可定制性的解决方案,请参阅此答案.

For a more technical and customizable solution, see this answer.

这篇关于TypeScript:深偏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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