在打字稿中创建数组类型

时间:2020-03-08 17:03:21

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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

我认为这里有一个错字。 在那里声明的是-对于指定的结构,总是有一个SINGLE项。

我可以假设目的是声明可以包含从0到N个已定义结构项的数组,那么语法应如下所示:

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