You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 11:54:04