gpt4 book ai didi

javascript - 如何在 typeScript 中声明一个采用多种类型的函数参数?

转载 作者:行者123 更新时间:2023-11-30 19:14:46 24 4
gpt4 key购买 nike

我有一个函数,它接受 3 种类型的数组作为其参数之一。该函数使用链中的另外两个函数将该数组作为参数传递给这些函数,并使用来自该数组特定索引的值。该数组是对象数组:

     renderFilters(title: string, filtersArray:Establishments[] | Cuisines[] | Category[] , filterName: string, filterType: string): ReactNode {
return (
...
filtersArray.map((obj: any, id: number) => {...}) // ERROR:This expression is not callable.
// Each member of the union type has signatures, but none of those signatures are compatible with each other.
{this.onHover(id, filtersArray, filterType)}

)
}



onHover(id: number, arr:Establishments[] | Cuisines[] | Category[], filterType: string) {
let obj:Establishments| Cuisines| Category = arr[id]; // object at index id
let fArr = arr;
fArr[id] = this.getnewFilterObj(filterType, obj);
...
this.setState({
establishmentList: fArr // ERROR: Types of property //'establishmentList' are incompatible.
// Type 'Cuisine[] | Category[] | Establishment[]' is not assignable to //type 'Establishment[]'.
})
}

private getnewFilterObj(type: string, obj: Establishments | Cuisines| Category) {
switch (type) {
case 'establishment':
return {
establishment: {
...obj.establishment, // ERROR: Property //'establishment' does not exist on type 'Cuisine | Category | Establishment'.
//Property 'establishment' does not exist on type 'Cuisine'.
hovered: !obj.establishment.hovered,
}
}
case 'category':
return {
categories: {
...obj.categories,
hovered: !obj.categories.hovered,
}
}
case 'cuisine':
return {
cuisine: {
...obj.cuisine,
hovered: !obj.cuisine.hovered,
}
}
default:
return obj;
}

render()函数中

 {this.renderFilters('cuisine', this.state.cuisineList, 'cuisine_name', 'cuisne')}
{this.renderFilters('categories', this.state.categoryList, 'name', 'category')}
{this.renderFilters('establishment', this.state.establishmentList, 'name', 'establishment')}

最佳答案

您应该按如下方式定义数组:

arr: (Establishments | Cuisines | Category)[]

这意味着数组可能包含所有 3 种类型的项

关于javascript - 如何在 typeScript 中声明一个采用多种类型的函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58114401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com