HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptreactCritical

TypeScript React: Access component property types

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
accessreacttypestypescriptcomponentproperty

Problem

npm package @types/react allows us to use React inside of our TypeScript applications.

We define components as

type Props = {...}

type State = {...}

export default class MyComponent extends React.Component {
}


Here we have to declare types for component props and state (in type variables).

After we declared that types, TypeScript uses that to validate the usage of our component (the shape of props passed to it).

I want to create a container around such a component. The container will reuse the props of the component. But in order to create another component with the same props I have to redeclare the types for props again. Or export them from the original component file and import into container:

// Original file
export type Props = {...}

// Container file
import MyComponent, { Props } from './original'


But I'm already importing the MyComponent from that file. This component already contains information about the props it consumes (thanks to type variables in React.Component).

How do I access that information from the component class itself without explicitly exporting/importing the type for props?

I want something like:

import MyComponent from './MyComponent'

type Props = MyComponent.Props //  {}

Solution

2019: noticed all answers above are quite outdated so here is a fresh one.

Lookup type

With newer TS versions you can use lookup types.

type ViewProps = View['props']


Despite being very convenient, that will only work with class components.

React.ComponentProps

The React typedefs ship with an utility to extract the type of the props from any component.

type ViewProps = React.ComponentProps

type InputProps = React.ComponentProps


This is a bit more verbose, but unlike the type lookup solution:

  • the developer intent is more clear



  • this will work with BOTH functional components and class components



All this makes this solution the most future-proof one: if you decide to migrate from classes to hooks, you won't need to refactor any client code.

Code Snippets

type ViewProps = View['props']
type ViewProps = React.ComponentProps<typeof View>

type InputProps = React.ComponentProps<'input'>

Context

Stack Overflow Q#43230765, score: 574

Revisions (0)

No revisions yet.