Skip to main content

Component Types

info

Component Types are only available in Flow v0.243.0+. If you are on an older version, please use React.AbstractComponent

Component Types have syntax similar to our runtime Component Syntax to make it easy to describe the type of a component. Component Types are most useful for writing library definitions.

Specifying Props

To declare a Component Type you can use the component keyword and list out the props your component expects.

1import * as React from 'react';2
3type ComponentType = component(numberProp: number, optionalProp?: string);4
5declare const Component: ComponentType;6
7<Component numberProp={3} />; // OK! optionalProp is optional

Like Component Syntax, Component Types also accept a rest parameter:

import * as React from 'react';

import type {Props as StarProps} from './Star';
import Star from './Star';

type BlueStarType = component(specificProp: string, ...StarProps);

Like Component Syntax, you can also declare an inline ref prop (but not in your rest parameter):

1import * as React from 'react';2import {useRef} from 'react';3
4type ComponentWithRef = component(someProp: number, ref: React.RefSetter<number>);5
6declare const Component: ComponentWithRef;7
8component Example() {9    const ref = useRef<number | null>(null);10    return <Component someProp={42} ref={ref}/>;11}

Specifying Render Types

You can also specify the Render Type for your component just like you can with Component Syntax

1import * as React from 'react';2
3component Foo() { return null }4type ComponentWithRenders = component() renders Foo;5
6declare const Component: ComponentWithRenders;7<Component /> as renders Foo; // OK!

Polymorphic Component Types

You can also write polymorphic Component Types, which is helpful for declaring "transparent" components:

1import * as React from 'react';2
3declare const TransparentComponent: component<T: React.Node>(children: T) renders T;4
5component Example() { return null }6
7const element: renders Example = (8    <TransparentComponent>9        <Example />10    </TransparentComponent>11); // OK!

Annotating Components with Component Types

Here's how you can describe the type of a Component Syntax component using a Component Type:

1import * as React from 'react';2
3component Foo() { return null }4
5component Example(someProp: number, ref: React.RefSetter<number>) renders Foo {6    return <Foo />;7}8
9Example as component(someProp: number, ref: React.RefSetter<number>) renders Foo; // OK!10
11
12component PolymorphicExample<T: React.Node>(children: T) renders T {13    return children;14}15
16PolymorphicExample as component<T: React.Node>(children: T) renders T; // OK!