I have this simple typescript code for react
type fruitCode = 'apple' | 'banana'
interface fruitList {
name: fruitCode
}
const [arr, setArr] = useState<fruitList[] | []>([])
useEffect(() => {
const arrList = [{
name: 'apple'
}, {
name: 'banana'
}];
//error?
setArr(arrList)
}, [])
demo https://codesandbox.io/s/react-typescript-forked-gi6fw?file=/src/App.tsx:103-391
how can I restrict my property value is either 'apple' and 'banana'?
Typescript cannot infer the type for arrList so set it directly
const arrList: fruitList[] = [
// ...
]
I would also remove | [] from the state type definition as it is redundant; an empty array still satisfies the <fruitList[]> requirement.
const [arr, setArr] = useState<fruitList[]>([])
Finally, your interfaces and types should not be part of the component. Move them above App
type fruitCode = "apple" | "banana";
interface fruitList {
name: fruitCode;
}
export default function App() {
// ...
}
You'll notice there are no warnings about your useEffect dependencies after this.