Javascript 如何在同一声明中使用多个类型和必需的道具?
我正在尝试使用此类型:Javascript 如何在同一声明中使用多个类型和必需的道具?,javascript,reactjs,typescript,ecmascript-6,Javascript,Reactjs,Typescript,Ecmascript 6,我正在尝试使用此类型: type DataTypes = | Link | Event | People | Article | Department | PageSearch | OfficeSearch | CatalogSearch | DocumentSearch | KnowledgeSearch; 如果我这样做,它会正常工作: const showOnTypeInQuery = ( onType: string, cardTy
type DataTypes =
| Link
| Event
| People
| Article
| Department
| PageSearch
| OfficeSearch
| CatalogSearch
| DocumentSearch
| KnowledgeSearch;
如果我这样做,它会正常工作:
const showOnTypeInQuery = (
onType: string,
cardType: (dataType: any[]) => ReactElement,
dataType: DataTypes[]
): ReactElement | null => {
if (typeInQuery === 'all' || typeInQuery === onType) {
return cardType(dataType as DataTypes[]);
}
return null;
};
const getPeopleCards = (people: People[]): ReactElement => {
return (
<ComponentToShow
data={people}
heading="People"
>
{people.map((p: People) => (
<PeopleCard
people={p}
isFetching={isFetchingData}
/>
))}
</ComponentToShow>
);
};
return showOnTypeInQuery('people', getPeopleCards, people);
在DataTypes
type中,我将所有这些类型都放在同一个声明中,因为我需要在函数showntypeinquery
中将它们作为参数使用。DataTypes
类型中的那些类型包含所需的道具,但我认为用管道分离这些类型会有好处
那么我做错了什么呢?您不能将类型为
People[]=>ReactElement
的函数置于需要DataTypes[]=>ReactElement
的位置,因为您的函数可能会接收到一个Link
类型参数,而它不知道如何处理它,因为它只能处理人
类型。
我不太确定您想在这里实现什么,但是如果您想对多个类型(如
Link、Event、People)重用showOnTypeInQuery,在您的示例中,一个解决方案是使用泛型(如
const showOnTypeInQuery = <T extends DataTypes>(
onType: string,
cardType: (dataType: T[]) => ReactElement,
dataType: T[]
): ReactElement | null => {
if (typeInQuery === 'all' || typeInQuery === onType) {
return cardType(dataType);
}
return null;
};
showOnTypeInQuery('people', getPeopleCards, people);
const shownTypeInQuery=(
onType:string,
cardType:(数据类型:T[])=>ReactElement,
数据类型:T[]
):ReactElement | null=>{
if(typeInQuery=='all'| | typeInQuery===onType){
返回卡片类型(数据类型);
}
返回null;
};
showOnTypeInQuery('people',getPeopleCards,people);
const showOnTypeInQuery = <T extends DataTypes>(
onType: string,
cardType: (dataType: T[]) => ReactElement,
dataType: T[]
): ReactElement | null => {
if (typeInQuery === 'all' || typeInQuery === onType) {
return cardType(dataType);
}
return null;
};
showOnTypeInQuery('people', getPeopleCards, people);