Basics of Typescript in React

July 5, 2024

1. What is React.FC ?

1type ReactFC = ()=> React.ReactElement | null;
2
3const TestComponent: ReactFC = ()=>{
4 return null;
5};
6
7export const App: React.FC=()=>{
8 return <TestComponent />
9}
10
11

2. Function Arguments

Like we do with normal functions in Typescript

1type Numbers = {
2 x: number;
3 y: number;
4}
5
6function add(args: Numbers) {
7 return args.x + args.y;
8}
9
10

We can, pretty much do the same thing with functional components

1type Props = {
2children: React.ReactNode;
3}
4
5const Button : React.FC<Props> = ({children}) => {
6return(
7
8<button>{children}</button>
9);
10};
11

3. unknown vs any

1function test(someArgs: any): any {
2 return someArgs + 10;
3}
4
5const num = 1;
6const result = test(num);
7
8

this will complain, because we are returning any and it will not cause error (which it should, because someArgs could be a string or a bool here).

To fix this, we will use unknown instead of any.

4. Generics

Generics allow you to create reusable components and functions that work with different types.

1function test<T>(someArgs: T): T {
2 return someArgs;
3}
4

Here, T is a generic type parameter. The test function will accept an argument of type T and return a value of the same type.

Type Inference: TypeScript can infer the type of T based on the argument passed to the function.

1const num = 1;
2const result = test(num);
3

In this case, TypeScript infers that T is a number, so result will be of type number.

Explicit Type Specification: You can also explicitly specify the type when calling the function.

1const result = test<string>('hello');
2
3

This works because we are passing a string to the function that expects a string.

Example of Type Error If you specify a type that does not match the argument type, TypeScript will throw an error.

1const num = 1;
2const result = test<string>(num);
3

This will throw an error because the test function is explicitly told to expect a string, but a number is being passed as an argument.

Example with Operation Let's consider an example where generics make more sense with a specific operation:

1function identity<T>(arg: T): T {
2 return arg;
3}
4
5

Using the identity function with inferred types:

1const num = 1;
2const result = identity(num); // Type of result is number
3

Using the identity function with explicit types:

1const result = identity<string>('hello'); // Type of result is string
2
3

Incorrect type specification:

1const num = 1;
2const result = identity<string>(num); // Error: Argument of type 'number' is not assignable to parameter of type 'string'
3

Share this article