首页 > 解决方案 > 在打字稿中创建数组类型

问题描述

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

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))。此外,代码被缩短了。忽略缺少的括号或任何此类错误

标签: typescript

解决方案


typea或类型的形状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)

推荐阅读