how to set predefined string (enum) in react's useState? I tried:
const [color, setColor] =
React.useState<"red | blue">("blue");
but I got error of
Argument of type '"blue"' is not assignable to parameter of type '"red | blue" | (() => "red | blue")'.ts(2345)
demo https://codesandbox.io/s/react-typescript-forked-jmj6c?file=/src/App.tsx:85-148
CodePudding user response:
You are missing two double quotations in your type.
Instead of
"red | blue"
it should be
"red" | "blue"
CodePudding user response:
const [color, setColor] = React.useState<"red" | "blue">("blue");
or:
type Color = "red" | "blue";
const [color, setColor] = React.useState<Color>("blue");