如何用TypeScript条件映射类型实现除title外字段可选的类型
解决方案
你可以通过 TypeScript 的内置工具类型 Pick、Omit 和 Partial 组合实现需求,无需修改原有的 IBlogFields 接口:
// 原有的 IBlogFields 接口 interface IBlogFields { title: string; content: string; author: string; publishDate: Date; // 其他字段... } // 创建 OptionalExceptTitle 类型:保留 title 必填,其余字段转为可选 type OptionalExceptTitle = Pick<IBlogFields, 'title'> & Partial<Omit<IBlogFields, 'title'>>; // 修改后的 IBlogAttributes 接口 interface IBlogAttributes { attributes: OptionalExceptTitle; }
代码说明:
Pick<IBlogFields, 'title'>:从IBlogFields中提取必填的title字段Omit<IBlogFields, 'title'>:移除IBlogFields中的title字段,得到剩余所有字段Partial<...>:将上述移除title后的字段全部转为可选类型&:将两部分合并,最终得到「title 必填,其余字段可选」的类型
使用时,IBlogAttributes 的 attributes 属性会强制要求传入 title,而其他字段可传可不传。
内容的提问来源于stack exchange,提问作者Kadiem Alqazzaz
相关产品推荐
相关产品推荐

