Videos
What is the recommended way to define props in a component? Where can I find either React or typescript documentation on recommended format? I've read through the docs but couldn't find a recommendation, especially between inline vs using type (there are recommendations on type vs interface but not inline vs separating out the props).
using interface
interface DrawerProps {
header: string;
}
function Drawer({
header,
}: DrawerProps): React.JSX.Element {
return <></>;
}or using type
type DrawerProps = {
header: string;
};
function Drawer({
header,
}: DrawerProps): React.JSX.Element {
return <></>;or inline
function Drawer({
header,
}: {
header: string;
}): React.JSX.Element {
return <></>;
}
» npm install prop-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.