I have this specific type structure (derived from a third-party library):
type StackActionType = {
type: 'REPLACE';
payload: {
name: string;
key?: string | undefined;
params?: object;
};
source?: string;
target?: string;
} | {
type: 'PUSH';
payload: {
name: string;
params?: object;
};
source?: string;
target?: string;
} | {
type: 'POP';
payload: {
count: number;
};
source?: string;
target?: string;
} | {
type: 'POP_TO_TOP';
source?: string;
target?: string;
};
I am interested in inferring the remaining union types based on certain criteria. This can be achieved using the field key/name. For example:
const action: StackActionType = ...;
if("payload" in action) {
// The action is inferred with union types of: 'REPLACE', 'PUSH', 'POP' (since it contains the "payload" field), and 'POP_TO_TOP' is omitted
}
However, I am looking for a way to achieve this using the field value instead of the field name, like so:
if(["PUSH", "REPLACE"].includes(action.type)) {
// Here, the action should only infer the union of 'REPLACE' & 'PUSH'. But unfortunately, this approach does not work as intended...
}
Any suggestions on how to accomplish this without directly copying or modifying the original type definition?
EDIT:
Here is an attempt using a type guard & if statement: Typscript sandbox