I am facing a scenario where I have the following structure:
selection: (InterfaceX | InterfaceY)[]
interface InterfaceX {
switch: boolean
propertyOne: number
}
interface InterfaceY {
switch: boolean
propertyTwo: number
}
The possible selections are:
{switch: true, propertyOne: 1} or {switch: false, propertyTwo: 2}
This setup leads to type errors when trying to handle it in a ternary operation:
selection.switch ? selection.propertyOne : selection.propertyTwo
TS2339: Property 'propertyOne' does not exist on type 'InterfaceY'.
And also results in:
TS2339: Property 'propertyTwo' does not exist on type 'InterfaceX'.
My question is, is there a way to specify which interface should be used on each side of the ternary operator? For example, if the switch is true use InterfaceX
, otherwise use InterfaceY
. I want to achieve this without modifying the existing interfaces. Thank you!
Here's a new example to illustrate the issue:
import React from "react";
export interface Props {
items: (InterfaceX | InterfaceY)[];
}
interface InterfaceX {
toggle: true;
sharedProp: string;
propertyX: string;
}
interface InterfaceY {
toggle: false;
sharedProp: string;
propertyY: string;
}
export const Picks = (props: Props) => {
const { items } = props;
return items.map(item =>
item.toggle ? (
<div>
{item.sharedProp} {item.propertyX} // Unresolved variable propertyX
</div>
) : (
<div>
{item.sharedProp} {item.propertyY} // Unresolved variable propertyY
</div>
)
);
};