0

I have a component SampleComponent.tsx:

import React from 'react';

type Props = { text: string };

export const SampleComponent: React.FC<Props> = ({text})=><div>{text}</div>;

SampleComponent.variant1 = ({text})=><div>{'variant1' + text}</div>;

When I try using SampleComponent.variant1 in other components, I get typescript error:

Property 'variant1' does not exist on type ...

Right now I am just casting type with as, but I think there is a better way.

How can I fix this?

Edit: How to type if I have dynamic variants - from 1 to 4 such - .variant1, .variant2, .variant3 and .variant4

1 Answer 1

1

Since you've said that Sample Component is an FC, react won't let you add any properties that aren't a part of FC. You can either expand the type you declare SampleComponent as, something like this:

export const SampleComponent: React.FC<Props> & {
  variant1: React.FC;
} = ({ text }) => <div>{text}</div>;

SampleComponent.variant1 = ({ text }) => <div>{"variant1" + text}</div>;

Or you can provide the type for the props but then let typescript figure out the rest by the way you use it:

const SampleComponent = ({ text }: Props) => <div>{text}</div>;

SampleComponent.variant1 = ({ text }: Props) => <div>{"variant1" + text}</div>;
Sign up to request clarification or add additional context in comments.

9 Comments

thanks! how to type if variant is dynamic such as variant1, variant2 etc.?
Do you know all the variants up front? Or do you need to be able to add arbitrary keys at runtime?
Do i understand correctly: you have an enum or union, and then you want to say "SampleComponent is an object with all the keys found in that enum/union, and each of the keys corresponds to a React.FC"?
To restrict an index type to certain keys you would do use in: [key in VariantType]: FC<Props>. Though i'm playing around with it a bit, and while the type is correct, typescript can't figure out that SampleComponent actually fulfills that type and so gives an error
Unfortunately i've got to go so i can't experiment with it some more. I'll check back later in the day
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.