0
votes

This is how I declare a state

const [input, setInput] = React.useState('')
const [goals, setGoals] = React.useState<string[]>([])

and this is my error code:

const addHandler = () => {
    setGoals((curGoals) => [...curGoals, { key: Math.random().toString(), value:input}])
}

This is a typescript hint:

Argument of type '(curGoals: string[]) => (string | { key: string; value: string; })[]' is not assignable to parameter of type 'SetStateAction<string[]>'. Type '(curGoals: string[]) => (string | { key: string; value: string; })[]' is not assignable to type '(prevState: string[]) => string[]'. Type '(string | { key: string; value: string; })[]' is not assignable to type 'string[]'. Type 'string | { key: string; value: string; }' is not assignable to type 'string'. Type '{ key: string; value: string; }' is not assignable to type 'string'.ts(2345)

I still don't understand why my code still outputs this error. I did use a string type of array with useState.

How can I resolve this error?

1

1 Answers

4
votes

You declare the state as being string[] this means it is an array of strings. So an item of this state must be a string. { key: Math.random().toString(), value: input } is an object with properties value and key property of type string.

You can change the state to be of type Array<{key: string, value: string}>

const [input, setInput] = React.useState('')
const [goals, setGoals] = React.useState<
    Array<{
        key: string,
        value: string
    }>
>([])

const addHandler = () => {
    setGoals((curGoals) => [...curGoals, { key: Math.random().toString(), value: input }])
}

Playground Link