Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda