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
Your
step
has a type ofnumber
, which can’t be used to indextypes
, sincetypes
only have1,2,3
. So you can manually typestep
to be akeyof types
:Since
step
is a number you will also need the keys:When indexing an object you’ll have to use the
keyof
operator.From the TypeScript Docs: