typescript - 打字稿:部分带有可选的子属性
问题描述
在打字稿中,是否有可能让方法 accept Partial<Something>
,其Something
子属性也都设置为可选?
export interface ISomething {
user: IUser;
}
export interface IUser {
id: number;
name: string;
}
export const myMethod = (something: Partial<ISomething>): void => {};
myMethod({ user: { id: 1, name: "" } }); //this works
myMethod({ user: { id: 1 } }); //this doesn't (but I want this to work too)
非常感谢 ;)
解决方案
您本质上是在寻找某种深度部分映射类型,例如
type DeepOptional<T> = T extends object
? DeepOptionalObject<T>
: T | undefined
type DeepOptionalObject<T> = { [P in keyof T]?: DeepOptional<T[P]> }
type Foo = { bar: Bar }
type Bar = { a: number, b: boolean[] }
const f1: Partial<Foo> = { bar: { a: 1 } } // NOPE
const f2: DeepOptional<Foo> = { bar: {a: 1 } } // OK
推荐阅读
- php - 无法从本地主机向服务器中的邮件 API 添加附件
- javascript - 如何查找是变量调用还是函数调用?
- node.js - 如何为节点 js 应用程序设置 SMTP 服务器以发送接收邮件?
- python - 即使遵循示例代码,导入 spaCy 神经核模块的另一个错误
- reporting-services - 如果图像字段值在 SSRS 的数据库中为空,如何显示默认文本?
- javascript - 无法读取未定义的属性“电子邮件”;firebase 身份验证();使用 Vuex
- image-processing - 这个 YUV420P 到 RGB 着色器的转换从何而来?
- python - 有没有办法返回在 any() 函数中返回 True 的元素的索引?
- java - 从 firebase 获取数据时,Recyclerview 的 Onscroll 无法正常工作
- php - 如何在php中为不同的页面分配不同的端口号