首页 > 解决方案 > 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

它不喜欢什么?

解决方案

  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

标签: javascriptreactjstypescript

解决方案


所以问题是你将 step 设置为一个对象而不是一个数字,

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

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

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

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

推荐阅读