How to set a union in Typescript

1 week ago 7
ARTICLE AD BOX

I am using React/Typescript, which means I can't use enum due to erasablesyntaxonly.

So, following the advice from this question I'm using a type like so:

type COLORING_MODE = "Interp2Colors" | "SingleColor" | "AlternateColors";

and declaring some state like so:

const [coloringMode, setColoringMode] = useState<COLORING_MODE>("Interp2Colors");

Now I need to create some radio-button inputs, but I haven't found a strongly-typed way to do so. I can do this:

<input type="radio" value="Interp2Colors" checked={coloringMode === "Interp2Colors"} onChange={e => setColoringMode(e.target.value as COLORING_MODE)} />

But I'd like a way to specify the values on that line which ensure that they belong to the COLORING_MODE type, so typos are flagged at compile time.

What's a clean way to address this?

Read Entire Article