Common Prop Types in TypeScript and React

Published on Jun 29, 2021

2 min read

TYPESCRIPT

All primitives in JS are available in TS.

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.

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

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

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:

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:

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:

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

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

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:

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

More Posts

Browse all posts

Aman Mittal author

I'm a software developer and a technical writer. In this blog, I write about Technical writing, Node.js, React Native and Expo.

Currently, working at Expo. Previously, I've worked as a Developer Advocate, and Senior Content Developer with companies like Draftbit, Vercel and Crowdbotics.


Copyright ©  2019-2022 Aman Mittal · All Rights Reserved.