Extract the Proptypes from a React-Component in Typescript
When I write React-Components in Typescript, I typically do something like this:
Example.tsx
tsx
import React from 'react'
export type ExampleProps = {
text: string
propB: number
}
const Example: React.FC<ExampleProps> = ({ text }) => {
return <div>{ text }</div>
}
export default Example
This way anyone using my component can also import it’s Props as a type which makes it easier to encapsulate it in another component. For example:
Wrapper.tsx
tsx
import React from 'react'
import Example, { ExampleProps } from './Example'
export type WrapperProps = Omit<ExampleProps, 'text'>
const Wrapper: React.FC<WrapperProps> = (props) => {
return <Example {...props} text="Fixed text" />
}
export default Wrapper
Sadly not every developer does this and you might end up wanting to refer to the Proptypes of another Component that has not exported them. In this case you can use generics to extract the Proptypes from the Component.
ExtractProps.ts
typescript
export type ExtractProps<T> = T extends React.Component<infer P> | React.FC<infer P> ? P : never
Using this line of code, I could also write the Wrapper-Component without referring to ExampleProps:
Wrapper2.tsx
tsx
import React from 'react'
import Example from './Example'
import { ExtractProps } from './ExtractProps'
export type WrapperProps = Omit<ExtractProps<Example>, 'text'>
const Wrapper: React.FC<WrapperProps> = (props) => {
return <Example {...props} text="Fixed text" />
}
export default Wrapper
Post-Meta
- Published: March 23, 2021
- Last modified: November 1, 2022
- Tags: react react-native typescript
Comments
Hui boo says:
Thanks! Very helpful
replies