I have a component which renders different elements based on a specific property, called type. It could have type definitions like this:
interface CommonProps {
size: 'lg' | 'md' | 'sm';
}
interface SelectInputProps extends CommonProps {
type: 'select';
options: readonly Option[];
selected: string;
}
interface TextInputProps extends CommonProps {
type: 'text';
value: string;
};
type InputProps = (SelectInputProps | TextInputProps) & ExtraProps;
function Field(props: InputProps): JSX.Element;
Now in my own component, I will access the properties of this component, like so:
import { ComponentProps } from 'react';
type FieldProps = ComponentProps<typeof Field>;
function MySpecialField(props: FieldProps) {
if (props.type === 'select') {
// this works
const { options, selected } = props;
}
return <Field {...props} />
}
This works absolutely fine. It knows in my if block that props is SelectInputProps. However, I made one small change and it appeared to completely break this mode of using the discriminated union.
type FieldProps = Omit<ComponentProps<typeof Field>, 'size'>;
In practice, here is what is happening
Why is this happening? Is there a way to fix it?