Home > Back-end >  Store a React.FC in a generic typed variable
Store a React.FC in a generic typed variable

Time:09-08

I want to find a way to store any React.FC in a variable.

So, I wrote the following code:

type CompoDefinition = {
    Compo: React.FC
}
type CompoAProps = {
    a: string
}
function CompoA(props: CompoAProps) {
    return <div>{props.a}</div>
}
type CompoBProps = {
    b: number
}
function CompoB(props: CompoBProps) {
    return <div>{props.b}</div>
}
const F: CompoDefinition = {
    Compo: CompoA
}

Now, I get the following error: Type '(props: CompoAProps) => Element' is not assignable to type 'FC<{}>'

It seems that React.FC is understood as React.FC<{}> which I understand, but I don't know how to resolve my issue: how to declare a variable that can be affected with "any React.FC"?

I could use React.FC<any> but my linter is not happy with it.

CodePudding user response:

You could try that and see if your linter says anything:

type CompoDefinition<T = any> = {
  Compo: React.FC<T>;
};

CodePudding user response:

I finally got what I wanted by typing my FC properties like that:

type GenericProps = {
  [key: string]: unknown;
};

type CompoDefinition = {
    Compo: React.FC<GenericProps>
}

(...)
  • Related