![](/img/trans.png)
[英]React/Typescript: Property 'id' does not exist on type 'object'
[英]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
它不喜歡什么?
解決方案:
interface useStepType {
step: any,
navigation: any,
}
從
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.