Generic component with default type

Viewed 615

In a TSX file, a generic component can be defined:

const MyComponent = <A,>() => <p>my component</p>

Note the , after A.

Now if I want A to be string by default, one would naturally assume that the above should be written:

const MyComponent = <A=string,>() => <p>my component</p>

Except this does not work.

What am I missing?

2 Answers

The best solution I could find was to define it as a normal function instead:

const MyComponent = function <A = string>() {
  return <p>my component</p>;
};

While this is not functionally the same as an arrow function, my guess is that in the context of React, you probably won't care most of the time anyway.

How about:

const MyComponent = <string,>() => <p>my component</p>?

Any reason it wouldn't work?

Related