Reputation: 91
What happens inside of a React Functional Component that affects type narrowing?
type SelectField =
| {
multi?: false;
value?: string;
}
| {
multi: true;
value?: (string | { [key: string]: any })[];
};
Using the above type, shouldn't Typescript be able to infer the type of value
in a ternary statement?
Example:
const hasValue = multi ? !!value?.length : !!value;
Shouldn't the type of value
in the truthy branch resolve to an array, and a string in the falsy branch? Instead, the type of value
resolves to a union of all possible values (string | string[] | {[key: string]:any}[] | undefined
) on either side of the ternary. If that is not the case, is there a way get Typescript to understand the relationship between multi
and value
?
The hasValue
logic is inside of a React Functional Component that I'm working on. Troubleshooting further, I found that outside of the component, the logic works as expected: resolving value
based on the value of multi
.
Upvotes: 0
Views: 39