Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is `Union` of strings and `string` achievable?

Is they’re a way to have an union of string type that accepts some specific strings AND string ?

type AcceptsWithString =
 | 'optionA'
 | 'optionB'
 | 'optionC'
 | string

playground

The aim here is to have a type that offer auto completion for inputs (list can be long and we can make errors easily in some cases) AND also any string ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I do know of a trick which can be used to confuse the IDE into still showing individual strings as autocomplete suggestions. There’s no guarantee that this will work for ever, but it works as of the current versions of typescript:

type AcceptsWithString =
 | 'optionA'
 | 'optionB'
 | 'optionC'
 | string & {}

string & {} doesn’t have any properties that string doesn’t already have, so you can still assign any string to this. But it confuses the editor enough that it can’t be sure that "optionA" and the others are redundant, so it keeps showing them.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading