Typescript React: Access component property types
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<typeof View>
type InputProps = React.ComponentProps<'input'>
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.
Starting with TypeScript 2.8, you can use conditional types, e.g. given:
interface MyComponentProps { bar: string; }
declare const MyComponent: React.Component<MyComponentProps>;
interface MyComponentClassProps { bar: string; }
declare const MyComponentClass: React.ComponentClass<MyComponentClassProps>;
interface MyStatelessComponentProps { bar: string; }
declare const MyStatelessComponent: React.StatelessComponent<MyStatelessComponentProps>;
We can define these helpers:
type GetComponentProps<T> = T extends React.ComponentType<infer P> | React.Component<infer P> ? P : never
And use them like so:
// $ExpectType MyComponentProps
type MyComponentPropsExtracted = GetComponentProps<typeof MyComponent>
// $ExpectType MyComponentClassProps
type MyComponentClassPropsExtracted = GetComponentProps<typeof MyComponentClass>
// $ExpectType MyStatelessComponentProps
type MyStatelessComponentPropsExtracted = GetComponentProps<typeof MyStatelessComponent>
Update 2018-12-31: this is now available in the official React typings via React.ComponentProps
.