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

如何在TypeScript中获取ReceiptEnum的嵌套Action类型?

TypeScript中如何从联合类型提取特定成员的嵌套类型

你当前定义的ReceiptEnum是联合类型,TypeScript对联合类型的索引访问有严格限制:只有当联合类型的所有分支都包含某个属性时,才能通过联合类型['属性名']的方式直接获取类型。显然你的ReceiptEnum里,一个分支有Action属性,另一个只有Data属性,所以直接用ReceiptEnum['Action']会报错。

下面提供几种可行的解决方法:

方法一:提前单独定义嵌套类型(推荐)

把Action对应的嵌套类型抽离出来单独定义,后续既可以复用,也能直接引用,代码可读性更强:

// 先单独定义Action的具体类型
export type ReceiptAction = {
    actions: Action[];
    gasPrice: string;
    inputDataIds: string[];
    outputDataReceivers: string[];
    signerId: string;
    signerPublicKey: string;
};

// 基于抽离的类型定义联合类型
export declare type ReceiptEnum = {
    Action: ReceiptAction;
} | {
    Data: {
        data: string;
        dataId: string;
    };
};

// 直接使用抽离的类型声明变量
const data: ReceiptAction = {
    actions: [],
    gasPrice: "",
    inputDataIds: [],
    outputDataReceivers: [],
    signerId: "",
    signerPublicKey: ""
};

方法二:用条件类型提取已有联合类型的成员

如果无法修改原有的ReceiptEnum定义,可以通过条件类型筛选出包含Action属性的分支,再提取其嵌套类型:

// 定义通用工具类型:提取联合类型中含指定属性的成员的属性类型
type ExtractNestedType<T, K extends string> = T extends Record<K, infer U> ? U : never;

// 提取ReceiptEnum里Action对应的嵌套类型
type ReceiptActionType = ExtractNestedType<ReceiptEnum, 'Action'>;

// 使用提取后的类型
const data: ReceiptActionType = {
    actions: [],
    gasPrice: "",
    inputDataIds: [],
    outputDataReceivers: [],
    signerId: "",
    signerPublicKey: ""
};

这里的条件类型会遍历ReceiptEnum的每个分支,判断分支是否包含指定属性Action,如果是就推断该属性的类型为U,最终返回符合条件的类型。

方法三:临时类型断言(不推荐)

如果只是临时场景使用,可以用类型断言快速获取类型,但这种方式缺乏类型检查,容易引入错误:

const data = {} as ReceiptEnum extends { Action: infer U } ? U : never;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:18:29