Home > Mobile >  Type any is not assignable to type never
Type any is not assignable to type never

Time:06-09

I'm just learning Typescript and also React, so I am new to this and I tried many things, I'm getting this error at -...attributes-, but I don't know how to set its type when it is in useState.

    const [tableAttributes, setTableAttributes] = useState({
        attributes: [],
    })

    const handleChange = (e) => {
        // Destructuring
        const { value, checked } = e.target
        const { attributes } = tableAttributes

        console.log(`${value} is ${checked}`)

        // Case 1 : The user checks the box
        if (checked) {
            setTableAttributes({
                attributes: [...attributes, value],
            })
        }

CodePudding user response:

You need to type the state, or else ts does not know what the attributes array is:

 const [tableAttributes, setTableAttributes] = useState<{attributes: string[]}>({
        attributes: [],
    })

Here we tell ts, that tableAttributes is an object with attributes as a string array.

Since I don't know, what the array actually is, you might need to change it to be boolean, number or what you what it to be in this case.

  • Related