T3 interblag real-estate

Typescript Hacks #1: String Suggestions

April 15, 2022

A cool thing about string unions is that they give you code completion in Visual Studio Code.

Though obviously, a string union is different from the type string and so variables of the type can only hold a certain set of string values.

We might conceive of cases where you want your variables to be able to hold any string, but you still want autocompletion, or "suggestion", of certain values. Simply adjoining the type string will not work, because the typescript compiler will simplify the entire thing down to string.

This is because "aardvark" is a subtype of string, and therefor "aardvark" | string is indistinguishable from string, which the compiler is smart enough to know.

The way out is to adjoin a type which we know is equivalent to string, but the compiler does not.

Look ma, no errors!


PS: Thanks to Alexendoo over at libera.chat for finding this very elegant solution to my problem.