【问题标题】:Creating an array type in typescript [closed]在打字稿中创建数组类型[关闭]
【发布时间】:2020-06-20 17:07:37
【问题描述】:

我在 typescript 中创建了一个数组类型,看起来像这样

export type RamenApi = [
    {
        "Brand": string,
        "Variety": string,
        "Style": string,
        "Country": string,
        "Stars": number,
        "Top Ten": string
    }
]

现在,在我对数组进行排序和过滤的地方之一,我收到以下错误

Property '0' is missing in type '{ "Brand": string; "Variety": string; "Style": string; "Country": string; "Stars": number; "Top Ten": string; }[]' but required in type 'RamenApi'

知道为什么我会收到以下错误以及如何解决它吗?

  type Props = {
        searchData: RamenApi, 

    const [filteredSearch, setFilteredSearch] = useState<RamenApi | null>(null)


 const {searchData} = props
            const tempFilteredSearch = []
                for (let i=0; i<searchData.length; i++) {
                    const currentResponse = searchData[i]
                    const searchVariable = currentResponse["Variety"].toLowerCase() + currentResponse["Brand"].toLowerCase() + currentResponse["Country"]
                    if (searchVariable.indexOf(text) > - 1) {
                        tempFilteredSearch.push(currentResponse)
                    }
                }
                setFilteredSearch(tempFilteredSearch.slice(0,5))

这是我收到错误setFilteredSearch(tempFilteredSearch.slice(0,5)) 的地方。此外,代码被缩短了。忽略缺少的括号或任何此类错误

【问题讨论】:

  • 如果没有看到该错误消息所引用的代码,任何人都无法回答这个问题。请写minimal reproducible example
  • 您定义的类型的意思是“包含一个元素的数组,并且该元素是具有字段的对象:字符串类型的“品牌”,“品种”......”。但是,您尝试将包含多个项目的数组设置为您的类型的状态
  • @Shlang 好的,那么我如何创建我的类型以包含多个项目?
  • 我不确定我是否理解您想要实现的目标。如果你只想拥有一个字符串数组,它是string[],如果你想确保只有有限的字符串值集可以放入数组,它是("Brand" | "Variety" ...)[]

标签: typescript


【解决方案1】:

type 或类型 interface 的形状将与该数组中的对象相同并且很可能相同。

创建类似的东西

export type RamenApi = {
        Brand: string,
        Variety: string,
        Style: string,
        Country: string,
        Stars: number,
        TopTen: string
    }

然后

searchData: RamenApi[], 

const [filteredSearch, setFilteredSearch] = useState<RamenApi[] | null>(null)

【讨论】:

    【解决方案2】:

    我认为有一个错字。 那里声明的内容 - 是一种总是有一个指定结构的单个项目的类型。

    我可能假设其意图是声明可能具有 0 到 N 个已定义结构的数组,那么语法应该是这样的:

    export type RamenApi = {
        "Brand": string,
        "Variety": string,
        "Style": string,
        "Country": string,
        "Stars": number,
        "Top Ten": string
    }[]
    

    【讨论】:

      猜你喜欢
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-13
      • 2019-03-03
      • 2017-02-20
      • 1970-01-01
      相关资源
      最近更新 更多