如何防止Union类型在TypeScript中期望不相关的键?



我有一个函数getRespectiveConfig()返回一个由我需要返回的所有类型组成的Union类型:

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>; // *Answer will probably require me to change this?
export const getRespectiveConfig = (
nodes: Node[] | undefined,
): RespectiveConfig | undefined => {
return determineAndReturnRespectiveConfigType(nodes); // Assume this returns type - AlphaConfig or BetaConfig
};

下面的Modal如何接收道具currentlyEditingConfig:

interface Props {
currentlyEditingConfig: BetaConfig | undefined;
}

下面是它的用法&问题在哪里。currentlyEditingConfig是一个希望接收BetaConfig的道具,这在技术上是RespectiveConfig中可能的类型之一,然后我收到一个错误,上面写着"属性'id'在类型'AlphaConfig'中缺失,但在类型'BetaConfig'中需要。":

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

我假设我在第一个代码块中标记了*的地方就是问题所在,我试图使用Pick<K, T>的变体,但无法弄清楚。

有关线程:

  • 将typescript接口属性类型转换为union
  • 如何传递可选参数,而强制一个要在TypeScript中传递?

这是我尝试的解决方案(我假设的hack) -当调用currentlyEditingConfigprop的Modal时,我必须这样做:

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

任何合适的解决方法都是非常感谢的。

最新更新