[英]React & Typescript: Property 'id' does not exist on type 'number'
Hello everyone who came to help.大家好,前来帮忙的人。 The code compiles and works, but TypeScript throws an error that Property 'id' does not exist on type 'number'.
代码可以编译并且可以工作,但是 TypeScript 会抛出一个错误,即“数字”类型上不存在属性“id”。 If you look deep into the hook, you can see that the
step
property is of type number
in its interface.如果您深入查看该钩子,您会发现
step
属性在其接口中属于number
类型。
The error occurs in this entry: step.此条目中出现错误:step. id
ID
import React, { useEffect, useState } from 'react'
import FirstStep from './steps/firstStep'
import {useForm, useStep} from 'react-hooks-helper'
interface IDefaultData2 {
id: string
}
const steps : any = [
{id: 'firstStep'},
{id: 'secondStep'},
{id: 'thirdStep'},
{id: 'confirm'},
{id: 'success'}
]
const UserForm: React.FC = () => {
const {step, navigation} = useStep({
steps,
initialStep: 0
})
console.log(typeof(step)) // object
console.log(typeof(step.id)) // string
console.log(step.id) // "firstStep"
return (
<>
{
(() => {
switch(step.id){
case 'firstStep': return <FirstStep/>
}
})()
}
</>
)
}
export default UserForm
What doesn't it like?它不喜欢什么?
SOLUTION :解决方案:
interface useStepType {
step: any,
navigation: any,
}
From从
const { step, navigation } = useStep({
steps,
initialStep: 0
})
To至
const { step, navigation }: useStepType = useStep({
steps,
initialStep: 0
})
Special thanks to Tomas Gonzalez特别感谢Tomas Gonzalez
So the issue is that you are setting step as an object and not as a number,所以问题是您将 step 设置为 object 而不是数字,
to solve this create a new interface for type step:为了解决这个问题,为类型步骤创建一个新接口:
interface stepType {
id: string,
}
interface useStepType {
step: stepType,
navigation: any,
}
and then try to set the step to this type然后尝试将步骤设置为此类型
const {step, navigation}: useStepType = useStep({
steps,
initialStep: 0
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.