levyndra
levyndra

Reputation: 33

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

Hello everyone who came to help. The code compiles and works, but TypeScript throws an error that Property 'id' does not exist on type 'number'. If you look deep into the hook, you can see that the step property is of type number in its interface.

The error occurs in this entry: 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

What doesn't it like?

SOLUTION:

  1. Add
interface useStepType {
    step: any,
    navigation: any,
}
  1. Edit

From

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

To

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

Special thanks to Tomas Gonzalez

Upvotes: 3

Views: 2993

Answers (1)

Tomas Gonzalez
Tomas Gonzalez

Reputation: 188

So the issue is that you are setting step as an object and not as a number,

to solve this create a new interface for type step:

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

and then try to set the step to this type

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

Upvotes: 1

Related Questions