【问题标题】:Function's parameters with different types不同类型的函数参数
【发布时间】:2021-02-18 04:41:30
【问题描述】:

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

我将组件的 Props 声明如下:

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

我试图在组件中传递的 onChange 格式如下:

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

所以我得到了以下错误:

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

我无法弄清楚为什么我收到错误,因为组件正在等待 onChange 将 newValue 作为 ContentManagementCategoryType[]OrganizationType[] > 我正在通过 ContentManagementType[] 传递一个 onChange。

有什么解决办法吗?

提前谢谢你。

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-23
      • 2019-12-25
      • 1970-01-01
      • 2015-05-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-06
      • 2020-12-28
      相关资源
      最近更新 更多