【问题标题】:Passing a function as a prop with different parameter types in React with Typescript在 React with Typescript 中将函数作为具有不同参数类型的道具传递
【发布时间】:2021-12-30 11:29:06
【问题描述】:

我正在尝试传递一个更新 React 状态的函数,但是 VSCode 警告我输入问题。错误是Type '(value: string) => void' is not assignable to type '(value: string | number) => void'. Types of parameters 'value' and 'value' are incompatible. Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'.Type '(value: number) => void' is not assignable to type '(value: string | number) => void'. Types of parameters 'value' and 'value' are incompatible. Type 'string | number' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'.

这是在这个代码块内:

<DropDownSelect
        options={blogTags}
        selectedOption={selectedBlogTag}
        allPosition="top"
        updateFunc={updateSelectedBlogTag}
      />
      <DropDownSelect
        options={["5", "10", "20", "50"]}
        selectedOption={selectedArticleCount}
        hideAll={true}
        updateFunc={updateArticleCount}
      />

DropDownSelect 有如下界面:

interface IDropDownSelect {
  options: string[];
  selectedOption: string | number;
  hideAll?: boolean;
  allPosition?: "top" | "bottom";
  updateFunc: (value: string | number) => void;
}

我有以下上下文:

export interface IBlogListContextData {
  blogList: IBlogListData[];
  blogListPage: number;
  setBlogListPage: (page: number) => void;
  updateBlogListPage: (page: number) => void;
  isLoading: boolean;
  fetchBlogList: (page?: number) => void;
  blogTags: string[];
  selectedBlogTag: string;
  selectedArticleCount: number;
  updateArticleCount: (value: number) => void;
  updateSelectedBlogTag: (value: string) => void;
}

export const blogListContextDefaultValue: IBlogListContextData = {
  blogList: [blogListDefault],
  blogListPage: 1,
  setBlogListPage: () => null,
  updateBlogListPage: (page: number) => null,
  isLoading: false,
  fetchBlogList: () => null,
  blogTags: [],
  selectedBlogTag: "all",
  selectedArticleCount: 5,
  updateArticleCount: (value: number) => null,
  updateSelectedBlogTag: (value: string) => null,
};

有没有一种方法可以将任一函数以字符串或数字类型传递给updateFunc?我试图避免使用any

【问题讨论】:

    标签: reactjs typescript react-typescript


    【解决方案1】:

    也许你可以重用 updateFunc 类型。

    updateSelectedBlogTag: IDropDownSelect['updateFunc']
    

    【讨论】:

    • 不知道为什么但它仍然不起作用,它仍然说类型'(值:数字)=> null'不可分配给类型'(值:字符串|数字)=> void'。参数 'value' 和 'value' 的类型不兼容。键入'字符串 | number' 不可分配给类型 'number'。类型“字符串”不可分配给类型“数字”。还有一个以字符串为类型的变体
    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 2021-06-01
    • 2020-03-12
    • 2012-10-27
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多