Rumah > Soal Jawab > teks badan
P粉8232680062023-08-16 16:02:42
Apabila mengindeks objek, anda perlu menggunakan operator keyof
.
Daripada dokumentasi TypeScript:
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()} )
P粉0088297912023-08-16 14:40:17
Andastep
具有number
类型,不能用于索引types
,因为types
只有1,2,3
。所以您可以手动将step
设置为keyof types
:
const [step, setStep] = useState<keyof types>(0)
Memandangkan step
ialah nombor, anda juga memerlukan kunci:
interface types { 0: JSX.Element; 1: JSX.Element; 2: JSX.Element; } const component: types = { 0: <Home />, 1: <Create />, 2: <Detail />, } return component[step] // 没有错误