I am working with a specific type that looks like this:
type Props = {
type: 'foo';
value: string;
} | {
type: 'baz';
value: number;
};
However, when using a switch
statement with the type
property in TypeScript, the program interprets the value
as string | number
.
function doThing(props: Props) {
const { type, value } = props;
switch(type) {
case 'foo':
return value.length;
case 'baz':
return value.toExponential(); // <-- Fails because value is `string | number`.
}
}
Is there a way to properly narrow down the type in this situation?