【发布时间】: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