Common Prop Types in TypeScript and React

Jun 29, 2021

2 min read

#react

All primitives in JS are available in TS.

TypeScript icon

1type Props = {
2 size: number;
3 name: string;
4 disabled: boolean;
5};

An object type is simply an empty object or an object with keys. An empty object can have any number of properties and values.

If the object is defined explicitly with keys, it will only accept those values. The shape of the object will remain certain.

TypeScript icon

1type Props = {
2 emptyObject: {};
3 product: {
4 id: string;
5 price: number;
6 };
7};

Using square brackets [], an array type is defined:

TypeScript icon

1type ListProps = {
2 items: string[];
3};

The prop items here only expects values in the array of string type. To define an array of objects of a certain shape:

TypeScript icon

1type ListProps = {
2 items: {
3 id: string;
4 name: string;
5 price: number;
6 }[];
7};

TypeScript does not asks you to define the shape of each object. Although, refactoring ListProps as below is valid:

TypeScript icon

1type Item = {
2 id: string;
3 name: string;
4 price: number;
5};
6
7type ListProps = {
8 item: Item;
9 items: Item[];
10};

Using union type, certain values for a prop can be described as:

TypeScript icon

1type Button = {
2 variant: 'primary' | 'danger' | 'info';
3 value: string | number;
4};

TypeScript cares when it comes to passing arguments on a function.

TypeScript icon

1type Props = {
2 onEventListener: () => void; // some times event listeners do not have return type
3 onChangeText: (title: string) => void;
4};

On a function, it is possible to define return type as inline type declaration:

TypeScript icon

1function add(x: number, y: number): number {
2 return a + b;
3}

⬅️ Previous: How To Integrate Firebase Authentication With an Expo App

Next: Prop types in React and TypeScript ➡️

Enjoyed this post? Sign up to my newsletter!

A periodic update about my recent blog posts and tutorials. Join 1300+ devs!

No spam, unsubscribe at any time!

Subscribe on Revue

HomeBlogNewsletterAbout meSpeakingEmail

©  2019-2022 Aman Mittal · All Rights Reserved