javascript - React & Typescript:“数字”类型上不存在属性“id”
问题描述
大家好,前来帮忙的人。代码可以编译并且可以工作,但是 TypeScript 会抛出一个错误,即“数字”类型上不存在属性“id”。如果您深入查看该钩子,您可以看到该step
属性number
在其接口中属于类型。
此条目中出现错误:step. 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
它不喜欢什么?
解决方案:
- 添加
interface useStepType {
step: any,
navigation: any,
}
- 编辑
从
const { step, navigation } = useStep({
steps,
initialStep: 0
})
到
const { step, navigation }: useStepType = useStep({
steps,
initialStep: 0
})
特别感谢Tomas Gonzalez
解决方案
所以问题是你将 step 设置为一个对象而不是一个数字,
为了解决这个问题,为类型步骤创建一个新接口:
interface stepType {
id: string,
}
interface useStepType {
step: stepType,
navigation: any,
}
然后尝试将步骤设置为此类型
const {step, navigation}: useStepType = useStep({
steps,
initialStep: 0
})
推荐阅读
- python - 谁能帮我解决径向分布函数的问题?
- javascript - 如何用 javascript jquery 剪切一段字符串?
- mysql - 触发自动插入同一行
- amazon-web-services - 将请求从 CloudFront 转发到 API Gateway 时出现 403 Forbidden 错误
- monitoring - 在 ubuntu 20.04 上配置 SNMP
- git - 更改所有 git subrepos 和提交的 GIT 子模块 URL
- ruby-on-rails - Ruby on Rails 测试
- botframework - 通过与 LUIS 和 QNA 绑定的 Microsoft Chatbot Composer (1.4.1) 接收 403(禁止)
- android - 如何在 Android 应用程序中使用 Jsoup 直接从网站显示搜索栏?
- python-3.x - 在任务调度程序中运行 python 脚本时出错