Javascript 如何在typeScript中声明接受多种类型的函数参数?
我有一个函数,它将3种类型的数组作为其参数之一。该函数使用链中的另外两个函数将该数组作为参数传递给这些函数,并使用该数组特定索引中的值。该数组是一个对象数组:Javascript 如何在typeScript中声明接受多种类型的函数参数?,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,我有一个函数,它将3种类型的数组作为其参数之一。该函数使用链中的另外两个函数将该数组作为参数传递给这些函数,并使用该数组特定索引中的值。该数组是一个对象数组: renderFilters(title: string, filtersArray:Establishments[] | Cuisines[] | Category[] , filterName: string, filterType: string): ReactNode { return (
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种类型的项,通过这样做,函数onHover()
和getNewObject()中的错误
之所以持续存在,是因为如果我想从objectobj:Establish | Councy | Category
访问键,这些键需要在所有界面中通用,这在这里是不可能的,因为Establishmsnts
,Cuisines
和Category
具有所有不同的键。所以你知道我面临着多个错误。完美的答案,谢谢。。我在CaseType['participants']|CaseType[]
问题上遇到了问题,必须以(CaseType['participants'][0]|CaseType][
的形式键入,您的回答帮助了我