TypeScript如何基于联合类型生成可选和必选两种自定义类型
实现方案
你可以直接使用 TypeScript 内置的工具类型 Partial<T> 实现属性可选的需求,原生 Record 生成的本身就是全必选属性的类型,修改后写法如下:
// 全可选属性的类型 export type LocalesCustomT = Partial<Record<LocalesT, string>> // 全必选属性的类型 export type LocalesInternalT = Record<LocalesT, string>
如果你需要用 interface 而非 type 定义,也可以通过继承实现:
export interface LocalesCustomI extends Partial<Record<LocalesT, string>> {} export interface LocalesInternalI extends Record<LocalesT, string> {}
以上写法生成的类型和你给出的目标效果完全一致,后续LocalesT的联合成员变更时,两个衍生类型会自动同步更新,无需手动维护属性列表。
内容的提问来源于stack exchange,提问作者user16754275
相关产品推荐
相关产品推荐

