search

Home  >  Q&A  >  body text

Valid Input Methods: A Guide to Conditional Rendering Controls

<p>I'm trying to enter conditional rendering, but it gives me the error: <code>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'.</code> Rendering is valid when everything is "any". </p> <pre class="brush:php;toolbar:false;">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()} )</pre> <p>Can anyone help me understand how to add types for this conditional rendering? </p> <p>I need to understand how to add types for this conditional rendering</p>
P粉550257856P粉550257856468 days ago500

reply all(2)I'll reply

  • P粉823268006

    P粉8232680062023-08-16 16:02:42

    When indexing an object, you need to use the keyof operator. From the TypeScript documentation:

    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()}
    )

    reply
    0
  • P粉008829791

    P粉0088297912023-08-16 14:40:17

    Your step has type number and cannot be used to index types because types only has 1,2, 3. So you can manually set step to keyof types:

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

    Since step is a number, you also need the key:

    interface types {
      0: JSX.Element;
      1: JSX.Element;
      2: JSX.Element;
    }
     const component: types = {
          0: <Home />,
          1: <Create />,
          2: <Detail />,
        }
     return component[step] // 没有错误

    reply
    0
  • Cancelreply