我正在尝试使用这种类型:
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
类型中的这些类型包含必需的属性,但我认为用管道分隔类型会成功。
那么我做错了什么?
最佳答案
您不能将类型为 People[] => ReactElement
的函数放置到需要 DataTypes[] => ReactElement
的位置,因为您的函数可能会收到,例如,一个 Link
类型参数,但它不知道如何处理它,因为它只能处理 People
类型。
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);
关于javascript - 如何在同一声明中使用具有必需属性的多种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59853878/