首页 > 解决方案 > 打字稿错误“0”不可分配给类型 QueryKey

问题描述

type DateRange = { start: Date; end: Date }
  type ParamType = {
    latitude: number | null | undefined
    longitude: number | null | undefined
    term: string
    dateRange: DateRange
  }

  const params: ParamType = {
    latitude: geo && geo.lat,
    longitude: geo && geo.lng,
    term,
    dateRange,
  }

  type QueryKey = (ParamType | string)[] | null | undefined
  const key: QueryKey = geo && geo.lat && geo.lng && ['all-results-cts', params]

Typescript'0' not assignable to type QueryKeykey变量赋值引发错误。代码有什么问题?

标签: reactjstypescript

解决方案


我认为这里有问题-

type QueryKey = (ParamType | string)**[]** | null | undefined

0不可分配给类型数组或 null 或未定义。 (ParamType | string)**[]**type 用于 (ParamType | string) 类型的数组。您需要检查获取键变量的类型并修复它或使用字符串类型调整 QueryKey。

type QueryKey = (ParamType | string)**[]** | null | undefined | string

推荐阅读