Julian Brooks
Julian Brooks

Reputation: 91

Typescript Type Inference Using a Boolean Property and Discriminating Unions

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

Answers (0)

Related Questions