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))
。此外,代码被缩短了。忽略缺少的括号或任何此类错误
解决方案
type
a或类型的形状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)
推荐阅读
- java - 为什么我的 java 应用程序在服务器上看不到 mariadb 驱动程序,即使它在本地运行良好?
- python - 绘制 dataFrame 中所有值的直方图
- python - 删除 Pandas 列中所有大于一的空格
- javascript - 学习 JS ......似乎被困在这个练习中......不知道我做错了什么
- tensorflow - Pytorch Autograd:运行时错误“只能为标量输出隐式创建grad”是什么意思
- json - 如何在 Angular 中的页面加载时发出 HTTP 请求(使用按钮)
- apache-flink - 如何获取 Flink 保存点 ID?
- jolt - 如何使用 Jolt 更改大型 Json 中一个字段的名称
- reactjs - 将来自 React 的数据推送到 MongoDB 的数组中
- c# - 获取字符数组中所有数字的总和