TypeScript problem: You need to support any string value, but you’d like...


TypeScript problem: You need to support any string value, but you’d like autocomplete support for common values.

Solution: Create a union with "string & {}" on the end.

Now you get autocomplete support for all values listed in the union, but can still enter any value.

TS Playground: https://www.typescriptlang.org/play/?#code/C4TwDgpgBAysCGwCuBnKBeKByA9pAdllAD7YDGANjihACZGkrABOAlvgOZQBkUA3gF8oAKGFkc+JlAAeALlgJkaTFhQ4AttBzAAFhGZQmiVEQD0pqABUdrNLajwyZCGGB0xEqSHlxjy7FhAA
Why “string & {}”? Because it keeps TS from widening the type to a plain string.

Full explanation: https://stackoverflow.com/a/75265010
If you prefer, here's another approach. Perhaps easier to understand, though it requires repeating the union:

type Status = 'open' | 'closed' | Omit<string, "open" | "closed">

https://www.typescriptlang.org/play/?#code/C4TwDgpgBAysCGwCuBnKBeKByA9pAdllAD7YDGANjihACZGkDyAtgJbAA8KwATq-gHMANFABEeCPlEkxlanVEA+AFDKyOfNygAPAFywEyNJiwoczaDmAALCDyjdEqIgHoXUACrXWaH1HhkZBBgwHRqGlog+nBOxthAA

h/t to @_4zuko

View original on X