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
相关产品推荐
相关产品推荐

