[英]typescript type error cannot assign string or undefined to string[]
Can't fix a typescript error, I check the console log and the regions that Set returns is an array of strings which is exactly what I have for region type in my state.无法修复 typescript 错误,我检查了控制台日志,Set 返回的区域是一个字符串数组,这正是我在 state 中的区域类型。 Why would this not work?为什么这行不通?
Code:代码:
const [regions, setRegions] = useState<string[]>([])
useEffect(() => {
if (areasOptions) {
const regions = [[...new Set(areasOptions.areas.map((item: ListObject) => item.region))]]
setRegions(regions) // Error
}
}, [areasOptions])
Error:错误:
Argument of type '(string | undefined)[][]' is not assignable to parameter of type 'SetStateAction'. '(string | undefined)[][]' 类型的参数不能分配给 'SetStateAction' 类型的参数。 [0] Type '(string | undefined)[][]' is not assignable to type 'string[]'. [0] 类型 '(string | undefined)[][]' 不可分配给类型 'string[]'。 [0] Type '(string | undefined)[]' is not assignable to type 'string'. [0] 类型 '(string | undefined)[]' 不可分配给类型 'string'。
This non-react example should work for you:这个非反应示例应该适合您:
function setRegions(abc: string[]) {
}
type ListObject = {
region: string
}
const areasOptions: {areas: ListObject[]} = {
areas: [
{region: "a"},
{region: "b"}
]
}
const regions = [...new Set(areasOptions.areas.map((item) => item.region))]
setRegions(regions)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.