首页 > 解决方案 > 不同类型的函数参数

问题描述

我有一个 onChange 函数,我将它作为道具传递给另一个 React 组件。

我将组件的 Props 声明如下:

  onChange: (newValue: ContentManagementCategoryType[] | OrganizationType[]) => void;

我试图在组件中传递的 onChange 具有以下格式:

  const updateFilterCategories = (newValue: ContentManagementCategoryType[]) => {
    setFilteredCategories(newValue);
  };

所以我收到以下错误:

类型 '(newValue: ContentManagementCategoryType[]) => void' 不可分配给类型 '(newValue: ContentManagementCategoryType[] | OrganizationType[]) => void'。参数“newValue”和“newValue”的类型不兼容。

我无法弄清楚为什么会出现错误,因为该组件正在等待一个带有newValue作为ContentManagementCategoryType[]OrganizationType[]的 onChange 并且我正在传递一个带有 ContentManagementType[]的 onChange 。

有什么解决办法吗?

先感谢您。

标签: reactjstypescript

解决方案


尝试这个

type ValueType = (ContentManagementCategoryType | OrganizationType)[]
onChange: (newValue: ValueType) => void;
const updateFilterCategories = (newValue: ValueType) => {
    setFilteredCategories(newValue);
  };

推荐阅读