英文:
TypeScript Generics with React Function Components
问题
You're encountering a TypeScript error because you're trying to pass a type argument (SpecificJobProps
) to SearchFilterJobs
, but it appears that the component is not set up to accept type arguments. You can modify the SearchFilterJobs
component like this to accept a type argument:
export const SearchFilterJobs = <T extends JobPosting>(props: SearchFilterJobsProps<T> & React.HTMLAttributes<HTMLDivElement>) => {
// ... component logic here
};
With this modification, you should be able to use it as you intended:
<SearchFilterJobs<SpecificJobProps> jobs={{ data: specificJobs }} />
This should resolve the TypeScript error you mentioned.
英文:
I have the following component structure:
export interface SearchFilterJobsProps<J = JobPosting> {
unwrap?: boolean;
jobs?: {
data: J[];
component?: React.ComponentType | React.ElementType;
};
searchMatchProps?: (keyof J)[];
}
export type SearchFilterJobsType<T = JobPosting> = React.FC<SearchFilterJobsProps<T>>;
export const SearchFilterJobs: SearchFilterJobsType = <Z extends JobPosting>(
{
jobs,
searchMatchProps,
className,
children,
...rest
}: SearchFilterJobsProps<Z> & React.HTMLAttributes<HTMLDivElement>) => { ... };
I have set it up like this, because I would like this component to handle various data structures. But I seem to have made some mistakes, because when I am attempting to use it:
<SearchFilterJobs<SpecificJobProps> jobs={{data: specificJobs}} />
TypeScript tells me: TS2558: Expected 0 type arguments, but got 1.
.
What am I doing wrong here?
答案1
得分: 0
以下是您提供的代码的翻译部分:
export const SearchFilterJobs: SearchFilterJobsType = ...
将为 SearchFilterJobsType 选择默认的类型参数。右侧的内容不重要 - 如果提供了类型注释,则必须完整。
在这种情况下,最简单的解决方案是在常量上使用 `satisfies` 而不是类型注释:
export type SearchFilterJobsType<T = JobPosting> = React.FC<SearchFilterJobsProps<T>>;
export const SearchFilterJobs = <Z extends JobPosting>(
{
jobs,
searchMatchProps,
className,
children,
...rest
}: SearchFilterJobsProps<Z> & React.HTMLAttributes<HTMLDivElement>) => {
... } satisfies React.FC<SearchFilterJobsProps<T>>;
希望这对您有所帮助。如果您需要任何进一步的翻译,请随时提问。
英文:
Something like:
export const SearchFilterJobs: SearchFilterJobsType = ...
will pick the default type param for SearchFilterJobsType. What's on the right side doesn't matter - the type annotation, if provided, must be complete.
Simplest solution in this case is to use satisfies
instead of an annotation on the constant:
export type SearchFilterJobsType<T = JobPosting> = React.FC<SearchFilterJobsProps<T>>;
export const SearchFilterJobs = (<Z extends JobPosting>(
{
jobs,
searchMatchProps,
className,
children,
...rest
}: SearchFilterJobsProps<Z> & React.HTMLAttributes<HTMLDivElement>) => {
... }) satisfies React.FC<SearchFilterJobsProps<T>>;
答案2
得分: 0
尝试将组件的const重写为函数声明。
我认为那应该可以工作
英文:
Try rewriting the component const to a function declaration.
I think that should work
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论