Search code examples
typescriptuse-state

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


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)

Solution

  • Use Partial to make all properties optional.

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