gpt4 book ai didi

javascript - react & typescript : Property 'id' does not exist on type 'number'

转载 作者:行者123 更新时间:2023-12-04 03:46:09 24 4
gpt4 key购买 nike

前来帮忙的大家好。代码可以编译并运行,但 TypeScript 会抛出一个错误,指出属性“id”在类型“number”上不存在。如果深入查看钩子(Hook),您会发现 step 属性在其接口(interface)中是 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

它不喜欢什么?

解决方案:

  1. 添加
interface useStepType {
step: any,
navigation: any,
}
  1. 编辑

来自

const { step, navigation } = useStep({
steps,
initialStep: 0
})

const { step, navigation }: useStepType = useStep({
steps,
initialStep: 0
})

特别感谢 Tomas Gonzalez

最佳答案

所以问题是您将步骤设置为对象而不是数字,

要解决这个问题,请为类型步骤创建一个新接口(interface):

interface stepType {
id: string,
}
interface useStepType {
step: stepType,
navigation: any,
}

然后尝试将步骤设置为这种类型

    const {step, navigation}: useStepType = useStep({
steps,
initialStep: 0
})

关于javascript - react & typescript : Property 'id' does not exist on type 'number' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65114827/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com