0

I have the following:

interface FormValues {
    max: number
}

Then, I do:

let [formValues, setFormValues] = useState({max: 5})

When I do console.log(formValues.max) I get a typescript error. How do I tell the destructuring call that formValues is of type FormValues and that setFormValues is a function?

This is not a duplicate of this:

Destructuring assignment in Typescript

or fo this:

Destructuring assignment via TypeScript in React

Neither of those answer the question

mikeb
  • 10,578
  • 7
  • 62
  • 120

1 Answers1

1

you can set the type of the state

export interface IValueType { max: number }

let [formValues, setFormValues] = useState<IValueType>({max: 5})
jgoday
  • 2,768
  • 1
  • 18
  • 17
  • This works, but how do I set the return type to be an array of `IValueType` and a function? – mikeb Mar 17 '19 at 13:53
  • if the return type would be an array : useState([{max: 5}]); – jgoday Mar 17 '19 at 14:05
  • Array like `[IValueType, function]`, an array of the value type in element 0 and a function in element 1 – mikeb Mar 17 '19 at 14:15
  • look at the typescript signature: function useState(initialState: S | (() => S)): [S, Dispatch>]; (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts) useState returns a tuple of a S value, and a Dispatch Function to update the state – jgoday Mar 17 '19 at 14:18