ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Tuesday, December 20, 2022

[FIXED] How can I get TypeScript IntelliSense to suggest valid completions in discriminated unions?

 December 20, 2022     conditional-statements, react-props, typescript   

Issue

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


Solution

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

  • Object member completions are offered from all union constituents even after union has been discriminated.
  • Union with non-distinct discriminating property breaks inference somewhat (confusing error messages, invalid intellisense

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



Answered By - Cody Duong
Answer Checked By - - Timothy Miller (ReactFix Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix