typescript - 打字稿避免交叉路口中可空值的重复类型
问题描述
我用这种类型构建了一个对象数组
export type MyDto = { prods: {id:string} | null } & {name: string};
比我过滤它以摆脱空类型,所以我有这种类型
export type MyFilteredDto = { prods: {id:string} } & {name: string};
有没有办法使用例如实用程序类型来避免重复(不使用其他类型)?
解决方案
您可以使用类型来指定类型的属性可以为空:
type WithNullableProp<T, K extends keyof T> = T | {
[k in K]: T[K] | null;
}
type MyFilteredDto = { prods: {id:string} } & {name: string};
type MyDto = WithNullableProp<MyFilteredDto, 'prods'>;
const test: MyDto = {
prods: null,
name: '1',
}
const test2: MyDto = {
prods: { id: 'a'},
name: '2'
}
const test3: MyFilteredDto = {
prods: null, // type error
name: '3',
}
WithNullableType
道具基本上只是说对象上的给定属性是可以为空的。
推荐阅读
- c# - 在 Azure 上托管时找不到位于我的根项目文件夹中的文件
- java - 如何通过方法创建两个具有相同类的bean?
- crystal-reports - 如果某些参数给定而某些参数为空,则在 Crystal Reports 中显示所有记录
- php - bitnami 堆栈 (ec2) 上的 Woocommerce Webshop:SSL 操作失败,代码为 1。OpenSSL 错误消息:错误:14090086
- tensorflow - 使用窗口数据集预测未来时期的时间序列值
- java - 这个 @Override for Arrays.sort 在 Java 中是如何工作的?
- sql - 取查询的最后一列,并将结果以逗号分隔在 1 列中
- reactjs - Gatsby:从电子邮件链接中消失的 url 参数
- vba - 如何将用户表单添加到此代码中而不是 msgbox?
- svelte - 如何在 Svelte 中获取组件的 dom 节点?