如何在 Typescript 中使用数组和对象设置状态?

How to setState with an Array and object in Typescript?

这就是我声明状态的方式

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

这是我的错误代码:

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

这是打字稿提示:

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)

我仍然不明白为什么我的代码仍然输出这个错误。我确实在 useState 中使用了字符串类型的数组。

我该如何解决这个错误?

您将状态声明为 string[] 这意味着它是一个字符串数组。所以这个状态的项目一定是string{ key: Math.random().toString(), value: input } 是一个对象,其属性 valuekey 属性 类型为 string

您可以将状态更改为 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