How to create React functional components in TypeScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Declaring type of props - see "Typing Component Props" for more examples
type AppProps = {
message: string;
}; /* use `interface` if exporting so that consumers can extend */

// Easiest way to declare a Function Component; return type is inferred.
const App = ({ message }: AppProps) => <div>{message}</div>;

// you can choose annotate the return type so an error is raised if you accidentally return some other type
const App = ({ message }: AppProps): React.JSX.Element => <div>{message}</div>;

// you can also inline the type declaration; eliminates naming the prop types, but looks repetitive
const App = ({ message }: { message: string }) => <div>{message}</div>;

// Alternatively, you can use `React.FunctionComponent` (or `React.FC`), if you prefer.
// With latest React types and TypeScript 5.1. it's mostly a stylistic choice, otherwise discouraged.
const App: React.FunctionComponent<{ message: string }> = ({ message }) => (
<div>{message}</div>
);

If your component is defined as a regular function with the function keyword, then you cannot use React.FunctionComponent keyword, because TypeScript does not support specify types for function declarations.

1
2
3
4
5
6
interface AppProps {
message: string;
}
export default function App({message}: AppProps) {
return <p>Hello:{message}</p>
}