Home > Software design >  How can I get TypeScript IntelliSense to suggest valid completions in discriminated unions?
How can I get TypeScript IntelliSense to suggest valid completions in discriminated unions?

Time:12-17

The objective is to create a checkbox UI component from a design in Figma. And according to the design, the outlined variant is only compatible with the size large, but solid is compatible with all sizes.

Therefore I'm trying to craft an interface where certain proptypes are depended on user input on other props on the same react component.

type ConditionalProps =
  | { variant: 'outlined'; size: 'large' }
  | { variant: 'solid'; size: 'small' | 'normal' | 'large' };

This is what i have came up, so far. And it almost does the job. When i set variant as outlined and size as small, typescript gives an error:

Type '{ variant: "outlined"; size: "normal"; }' is not assignable to type 'IntrinsicAttributes & ConditionalProps' 

But what I'm not really contempt with is; the IntelliSense suggest to use type 'small' | 'normal' | 'large' when the variant is set to outlined. See the image below to see what I mean. My question is if there is any way to get around of this issue? Or am I using the conditional type wrong in this case?

image of issue

CodePudding user response:

There is no way right now for only valid suggestions to show up. The IntelliSense doesn't know which is (so to speak) in a discriminated union like this. This is a known limitation:

It looks like there was an experiment to maybe fix this, but it never got anywhere. Free feel to open an issue at microsoft/TypeScript

  • Related