Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
typescript use preset value for property value in array object error?

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'?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

Edit React Typescript (forked)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!