【发布时间】:2019-09-26 18:12:20
【问题描述】:
我有一个函数,它将可以是 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')}
【问题讨论】:
标签: javascript reactjs typescript