1

I am using React with TypeScript in the following way:

interface MyComponentProps {
    ...
    ...
}

const MyComponent:FunctionComponent<MyComponentProps> = props => {
    ...
    ...
    ...
}

Now I need to define the following props type:

interface MyComponent2Props<T> {
    prop1: T,
    ...
}

I tried to define the component:

const MyComponent2<T>:FunctionComponent<MyComponent2Props<T>> = props => {
    ...
    ...
    ...
}

But this is incorrect syntax.

What is the correct way to define such component?

Naor
  • 23,465
  • 48
  • 152
  • 268
  • I don't have the rep to comment, but this is what I've found: [How to use generics in props in React in a functional component?](https://stackoverflow.com/questions/53958028/how-to-use-generics-in-props-in-react-in-a-functional-component) – alparius Sep 04 '19 at 21:54

2 Answers2

5

You could try something like this:

import * as React from "react";
import { render } from "react-dom";

import "./styles.css";

interface Props<T> {
  a: T;
}

const Component = <T extends {}>(props: Props<T>) => {
  return <div>{props.a}</div>;
};

function App() {
  return <Component a="testing" />;
}

const rootElement = document.getElementById("root");
render(<App />, rootElement);

You can view the example here.

Note the extends {} is necessary in a tsx file. See: What is the syntax for Typescript arrow functions with generics?

skovy
  • 5,430
  • 2
  • 20
  • 34
-3

Try this:

const MyComponent2 = <T>(props: SomeProps): FunctionComponent<MyComponent2Props<T>> => {}
ehutchllew
  • 940
  • 8
  • 14