Home > other >  How to setState with an object in Typescript? [Error ts(2345)]
How to setState with an object in Typescript? [Error ts(2345)]

Time:04-08

Interface

interface Info {
    name: string,
    brand?: string,
    category?: string,
    subCategory?: string
}

useState

const   [info, setInfo]     =   useState<Info | null>(null);

I'm able to successfully set the state of the name input

onChange={e => setInfo({...info,name:e.target.value.toLowerCase()})}

but for any other property of the Info object, I get an error.

onChange={e => setInfo({...info,category:e.target.value.toLowerCase()})}
------------------------------------------------------------------------
Argument of type '{ category: any; name?: string | undefined; brand?: string | undefined; subCategory?: string | undefined; }' is not assignable to parameter of type 'SetStateAction<Info | null>'.
  Type '{ category: any; name?: string | undefined; brand?: string | undefined; subCategory?: string | undefined; }' is not assignable to type 'Info'.
    Types of property 'name' are incompatible.
      Type 'string | undefined' is not assignable to type 'string'.
        Type 'undefined' is not assignable to type 'string'.ts(2345)

I get that this error is happening because the name field is compulsory & each setState call is expected to have the name property. Knowing that, how do I resolve this error ?

CodePudding user response:

you can use the as keyword:

onChange={e => setInfo({...info,category:e.target.value.toLowerCase()} as Info)}

CodePudding user response:

This is happening due to the fact that e.target.value.toLowerCase() might be returning undefined and the name type is set to string.

Either do - onChange={e => setInfo({...info,category:e.target.value.toLowerCase() || ''})}

OR

update your type definition to -

interface Info {
    name: string | undefined,
    brand?: string,
    category?: string,
    subCategory?: string
}
  • Related