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

165
Visualizações
Typing switch statement

I have a react component. That component recieves list, type. List is an array of objects. Type is just an optional enum string. Inside this component I have a function that's simply a switch case. I want to enforce a specific type in each CASE statement.

Simple example below. ERROR MESSAGE: : Property 'pk' does not exist on type 'combinedInterfaces'. Property 'pk' does not exist on type 'basicInterface'.

Array1:

[
  {some: {id: 1}, name: 'John'},
  {some: {id: 2}, name: 'Jan'},
]

Array2:

[
  {pk: 1, some: { id: 12}, name: 'John'},
  {pk: 2, some: { id: 13}, name: 'Jan'},
]

Rendering my components:

<MyComponent list={array1} />
<MyComponent list={array2} type={typesList.myType} />

Content of MyComponent

export enum typesList {
  myType = 'myType'
}

interface basicInterface {
  some: {
    id: number;
  },
  name: string;
} 

interface myTypeInterface extends basicInterface{
  pk: number;
}

type listType = Array<combinedInterfaces>

type combinedInterfaces = myTypeInterface | basicInterface;


type MyComponentProps = {
  list: listType,
  type: typesList
}

const MyComponent = ({list, type}: MyComponentProps) => {
  const handleType = (item: combinedInterfaces) => {
    switch (type) {
      case typesList.myType: {
        return {
          id: item.pk (ERROR HERE)
        }
      }
      default: {
        return {
          id: item.some.id
        }
      }
    }
  }

  const handledList = useMemo(() => list.map(item => handleType(item),[list])

  return (
    <>
      {handledList.map(item =>
        <div>
         {item.id}
        </div>
      )}
    </>
  )
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You should make a typecast for item, like this:

const MyComponent = ({list, type}: MyComponentProps) => {
  const handleType = (item: combinedInterfaces) => {
    switch (type) {
      case typesList.myType: {
        return {
          id: (item as myTypeInterface).pk
        }
      }
      default: {
        return {
          id: (item as basicInterface).some.id
        }
      }
    }
  }
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