4

I use React with Typescript and a functional approach.

const Divider: React.FunctionComponent<CardDividerProps> = (props: CardDividerProps) => (
   <div>
      divider
   </div>
);

const Card: React.FunctionComponent<CardProps> = (props: CardProps) => (
   <div>
      card
   </div>
);

Card.Divider = Divider; //Property 'Divider' does not exist on type 'FunctionComponent<CardProps>'.

If I remove the explicit type from the Card, it works. But I want to specify it with React.FunctionComponent... Is it possible?

I guess I can create a type:

type CardWithDividerComponent = {
    (props: CardProps): JSX.Element;
    defaultProps: CardProps;
    Divider: React.FunctionComponent<CardDividerProps>;
}

But is this the only solution? Is there any solution with React.FunctionComponent?

Nikolai
  • 555
  • 7
  • 17

1 Answers1

5

You are telling TypeScript that Card is a function with type React.FC. This type doesn't contain any property Divider, so TypeScript complains about that.

To fix the issue, you must tell TypeScript correct type of your component, something like this:

const Card: React.FunctionComponent<CardProps> & {Divider?: React.FunctionComponent<CardDividerProps>} = (props: CardProps) => (
   <div>
      card
   </div>
);

Card.Divider = Divider;
Drag13
  • 5,859
  • 1
  • 18
  • 42
  • Thanks for the answer. I didn't know that we can add properties with &. TypeScripts's OOP is really interesting, it's almost more flexible than C#'s where I have experience. – Nikolai Jul 28 '20 at 15:36
  • 1
    I have experience in both, and I would say (if we omit runtime reflection) TS more powerful than C#. But F# is more powerful than TS :) – Drag13 Jul 28 '20 at 15:39