繁体   English   中英

React & Typescript:“数字”类型上不存在属性“id”

[英]React & Typescript: Property 'id' does not exist on type 'number'

大家好,前来帮忙的人。 代码可以编译并且可以工作,但是 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

它不喜欢什么?

解决方案

  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

所以问题是您将 step 设置为 object 而不是数字,

为了解决这个问题,为类型步骤创建一个新接口:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM