【问题标题】:React & Typescript: Property 'id' does not exist on type 'number'React & Typescript:“数字”类型上不存在属性“id”
【发布时间】:2020-12-03 04:27:40
【问题描述】:

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

【问题讨论】:

  • 什么是useStep
  • Typescript 认为 step 是一个数字,但它实际上是一个对象
  • @CertainPerformance,我正在根据 youtube 教程 youtube.com/watch?v=HuJDKp-9HHc&t=157s 做多种形式。他在那里使用了 react-hook-helper 钩子。其中'useStep'是新的useTrafficLight,是一个更通用的步骤向导。您可以使用它来简化许多任务,例如多页输入表单或图像轮播。它具有自动前进功能,或通过调用上一个和/或下一个手动控制。
  • @user2258152,那么我该如何解决呢?这是错误
  • 请在问题本身中发布minimal reproducible example,包括useStep,这对于理解代码中发生的事情至关重要

标签: javascript reactjs typescript


【解决方案1】:

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

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

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

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

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

【讨论】:

  • step 应该默认输入为 any 吗?但如果 op 想要打字,那么可以这样做。
  • 这可以解决错误,但这是不好的做法,并且违背了打字稿的意义。在这种情况下,步骤应该是一个具有一个 id 属性的对象。我将导航设置为任何,因为我没有关于对象结构的信息。
  • op 没有为步骤分配编号,所以我怀疑错误来自他项目中的其他地方。
  • 我假设 typescript 将 step 推断为一个数字,但我们可以通过声明类型来覆盖它。
  • @TomasGonzalez,在您的解决方案中,过去的错误消失了,但出现了新的错误。错误文本:“类型‘UseStepResponse’不可分配给类型‘useStepType’。属性‘step’的类型不兼容。类型‘number’不可分配给类型‘stepType’。”但是,代码也可以编译。我刚刚删除了您的一个界面并将 step 属性设置为键入 any。发生以下情况: interface useStepType { step: any, navigation: any, } const { step, navigation }: useStepType = useStep({ steps, initialStep: 0 })
猜你喜欢
  • 2020-05-15
  • 1970-01-01
  • 2023-01-09
  • 2019-08-18
  • 1970-01-01
  • 2018-07-31
  • 2020-12-11
  • 2023-04-02
相关资源
最近更新 更多