Home > database >  Type error for initial empty object with useState (union type)
Type error for initial empty object with useState (union type)

Time:05-18

How can I set the types correctly for an initial empty object an interface?

interface IInputs {
  prop1: string
  prop2: string
  prop3: string
}

const [inputs, setInputs] = useState<IInputs | {}>({})

Gives the following error in the value attribute of the input:

Property 'prop1' does not exist on type '{} | IInputs'.
  Property 'prop1' does not exist on type '{}'.ts(2339)

CodePudding user response:

Use Partial to make all properties optional.

const [inputs, setInputs] = useState<Partial<IInput>>({})
  • Related