Categories
TypeScript Answers

How to add types of generic stateless component with React and TypeScript?

Spread the love

Sometimes, we want to add types of generic stateless component with React and TypeScript.

In this article, we’ll look at how to add types of generic stateless component with React and TypeScript.

How to add types of generic stateless component with React and TypeScript?

To add types of generic stateless component with React and TypeScript, we can create an interface that takes a generic type argument.

For instance, we write

interface IMyComponentProps<T> {
  name: string
  type: T
}

type MyComponentI<T = any> = React.FC<IMyComponentProps<T>>

const MyComponent: MyComponentI = props => <p {...props}>Hello</p>

const TypedComponent = MyComponent as MyComponentI<number>

to create the IMyComponentProps interface that takes the type argument T.

Then we can use that to create the MyComponentI<T = any> type set to React.FC<IMyComponentProps<T>>.

React.FC is the type for function components.

IMyComponentProps<T> is the props object’s type.

And then we can cast the type of MyComponent to whatever we want like

MyComponent as MyComponentI<number>

to set T to number.

Conclusion

To add types of generic stateless component with React and TypeScript, we can create an interface that takes a generic type argument.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *