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

如何在TypeScript可辨识联合类型中保留type并设其他字段为可选?

保留可辨识联合类型标识字段的Partial工具类型实现

你可以通过自定义工具类型,针对可辨识联合的每个分支单独处理,保留type字段的必填性,同时将其他字段转为可选。

实现方案

首先定义一个工具类型,用于保留指定字段的必填性,其余字段转为可选:

type PartialExcept<T, K extends keyof T> = {
    // 保留指定字段为必填
    [P in K]: T[P];
} & Partial<Omit<T, K>>; // 将剩余字段转为可选

然后利用TypeScript的分布式条件类型,对联合类型U的每个分支应用这个工具类型:

type PartialU = U extends infer Item ? PartialExcept<Item, 'type'> : never;

结果验证

此时PartialU的类型结构正是你需要的:

type PartialU = {
    type: 'a';
    attr1?: number;
} | {
    type: 'b';
    attr1?: string;
    attr2?: boolean;
} | {
    type: 'c';
    attr5?: object;
    attr6?: boolean;
}

简化写法(可选)

也可以用对象映射的方式直接实现,不需要额外定义PartialExcept:

type PartialU = {
    [Type in U['type']]: 
        { type: Type } & Partial<Extract<U, { type: Type }> extends infer T ? Omit<T, 'type'> : never>
}[U['type']];

内容的提问来源于stack exchange,提问作者Guillaume Racicot

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 05:23:18