skip to Main Content

I’m trying to type conditional rendering but it gives error Element implicitly has an 'any' type because expression of type 'number' can't be used to index type 'types'. No index signature with a parameter of type 'number' was found on type 'types'. The render works when everything is "any".

interface types {
  '0': JSX.Element;
  '1': JSX.Element;
  '2': JSX.Element;
}

export default function Economy(props: any) {
  const [step, setStep] = useState(0)

  const render = () => {
    const component: types = {
      '0': <Home />,
      '1': <Create />,
      '2': <Detail />,
    }
    return component[step]
  }
return (
   {render()}
)

Can anyone help me understand how to type this conditional render?

i need to understand how to type this conditional render

2

Answers


  1. Your step has a type of number, which can’t be used to index types, since types only have 1,2,3. So you can manually type step to be a keyof types:

    const [step, setStep] = useState<keyof types>(0)
    

    Since step is a number you will also need the keys:

    interface types {
      0: JSX.Element;
      1: JSX.Element;
      2: JSX.Element;
    }
     const component: types = {
          0: <Home />,
          1: <Create />,
          2: <Detail />,
        }
     return component[step] // no error
    
    Login or Signup to reply.
  2. When indexing an object you’ll have to use the keyof operator.
    From the TypeScript Docs:

    The keyof type operator
    The keyof operator takes an object type and produces a string or numeric literal union of its keys.

    interface types {
      '0': JSX.Element;
      '1': JSX.Element;
      '2': JSX.Element;
    }
    
    export default function Economy(props: any) {
      const [step, setStep] = useState<keyof types>("0")
    
      const render = () => {
        const component: types = {
          '0': <Home />,
          '1': <Create />,
          '2': <Detail />,
        }
        return component[step]
      }
    return (
       {render()}
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search