0

I have a function getRespectiveConfig() returning a Union type consisting of all the types I need to be return:

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
};

How Modal below receives the prop currentlyEditingConfig:

interface Props {
    currentlyEditingConfig: BetaConfig | undefined;
}

Here is how it is used & where the issue lies. currentlyEditingConfig is a prop expecting to receive BetaConfig which is technically one of the possible types in RespectiveConfig, I then receive an error that says "Property 'id' is missing in type 'AlphaConfig' but required in type 'BetaConfig'.":

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

I assume where I have marked * in the first code block is where the issue would lie, I have tried to use variations of Pick<K, T> but unable to figure it out.

Relevant threads:

jchua
  • 354
  • 1
  • 4
  • 15

1 Answers1

0

This is my attempted solution (a hack I assume) - When calling Modal with the currentlyEditingConfig prop, I had to do this:

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

Any proper solution greatly appreciated.

jchua
  • 354
  • 1
  • 4
  • 15
  • It is not correct solution as long as `getRespectiveConfig` could return `AlphaConfig` which is not expected by `currentlyEditingConfig` property. You are just forcing TypeScript to make think, this will be `BetaConfig`, which is not guaranteed. – Vladislav Kibenko Dec 20 '22 at 07:46
  • Thanks Vladislav Kibenko, I made an edit to my "solution" after your comment. – jchua Dec 20 '22 at 07:56
  • So the thing is `getRespectiveConfig` was meant to be generic for extracting various configs depending on the context. So I think if there were a proper way to fix this, it would be within the type declaration? - Where `RespectiveConfig` was declared – jchua Dec 20 '22 at 07:57
  • 1
    In my mind, you should create separate function extracting `BetaConfig` (`getBetaConfig`, for example) which will reuse `getRespectiveConfig` and check if it is really `BetaConfig`. For example, via checking if `id` property exists in received `RespectiveConfig`. – Vladislav Kibenko Dec 20 '22 at 08:02