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

TypeScript中如何避免联合类型匹配无关键引发的类型错误?

TypeScript联合类型适配问题

类型与函数定义

有一个返回联合类型的函数getRespectiveConfig(),相关类型及函数代码如下:

interface AlphaConfig {
    title: string;
}

interface BetaConfig {
    id: string;
}

export interface EncompassingConfig {
    alphaConfig?: AlphaConfig;
    betaConfig?: BetaConfig;
}

type ValueOf<T> = T[keyof T];
type RespectiveConfig = ValueOf<EncompassingConfig>; // *此处可能存在问题?

export const getRespectiveConfig = (
    nodes: Node[] | undefined,
): RespectiveConfig | undefined => {
    return determineAndReturnRespectiveConfigType(nodes); // 该函数实际返回AlphaConfig或BetaConfig类型
};

Modal组件属性要求

Modal组件的currentlyEditingConfig属性类型定义如下:

interface Props {
    currentlyEditingConfig: BetaConfig | undefined;
}

错误场景

在使用Modal时传入getRespectiveConfig的返回值,触发以下类型错误:

Property 'id' is missing in type 'AlphaConfig' but required in type 'BetaConfig'

使用代码如下:

<Modal
    currentlyEditingConfig={state.nodes ? getRespectiveConfig(state.nodes) : undefined}
/>

疑问

推测问题出在RespectiveConfig的类型定义行(标注*处),尝试过Pick相关类型变体但未解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:25:09