【发布时间】:2020-01-22 06:31:53
【问题描述】:
我正在尝试使用这种类型:
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);
在函数showOnTypeInQuery我有这个参数:
cardType: (dataType: any[]) => ReactElement
如果我更改为 cardType: (dataType: DataTypes[]) => ReactElement,,它将停止工作并引发以下错误:
ERROR in [at-loader] ./src/components/searchResult/searchResults.tsx:491:38
TS2345: Argument of type '(people: People[]) => React.ReactElement<any, string | ((props: any) => React.ReactElement<any, string | ... | (new (props: any) => React.Component<any, any, any>)> | null) | (new (props: any) => React.Component<...>)>' is not assignable to parameter of type '(dataType: DataTypes[]) => ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<...>)>'.
Types of parameters 'people' and 'dataType' are incompatible.
Type 'DataTypes[]' is not assignable to type 'PeopleModel[]'.
Type 'DataTypes' is not assignable to type 'PeopleModel'.
Property 'loginId' is missing in type 'Article' but required in type 'PeopleModel'.
在DataTypes 类型中,我将所有这些类型都放在同一个声明中,因为我需要在函数showOnTypeInQuery 中将它们作为将在某些时候使用的参数。 DataTypes 类型中的那些类型包含必需的道具,但我认为用管道分隔类型会成功。
那我做错了什么?
【问题讨论】:
标签: javascript reactjs typescript ecmascript-6