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

155
Views
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 answers
Answer question

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 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!