简体   繁体   English

typescript 类型错误不能分配字符串或未定义给字符串[]

[英]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.

相关问题 输入&#39;字符串| null&#39; 不能分配给类型 &#39;string | TypeScript 的未定义错误 - Type 'string | null' is not assignable to type 'string | undefined error with TypeScript 'string | 类型的参数 undefined' 不可分配给“string”类型的参数 - TypeScript 错误 - Argument of type 'string | undefined' is not assignable to parameter of type 'string' - TypeScript error 如何分配字符串| 在 TypeScript 中未定义为字符串? - How to assign string | undefined to string in TypeScript? 打字稿错误-类型&#39;string []&#39;不能用作索引类型 - Typescript error - Type 'string[]' cannot be used as an index type 打字稿推断错误 - 类型字符串的变量在 for 循环内更改为未定义 - Typescript inference error - variable with type string changes to undefined inside for loop 'string | 类型的参数 undefined' 不能分配给'string' 类型的参数。 typescript '严格' - Argument of type 'string | undefined' is not assignable to parameter of type 'string'. typescript 'strict' Typescript:类型参数'string | undefined' 不能分配给“string”类型的参数 - Typescript: Argument of type 'string | undefined' is not assignable to parameter of type 'string' 类型“字符串”不能分配给类型“UploadFileStatus | 不明确的' - Type 'string' cannot be assigned to type 'UploadFileStatus | undefined' 打字稿类型&#39;字符串&#39;不可分配给类型“错误 - Typescript Type ‘string’ is not assignable to type" error TypeScript 错误:类型“字符串”不可分配给排版类型 - TypeScript error: Type 'string' is not assignable to type for Typography
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM