Skip to content

Common Prop Types in TypeScript and React

Published:

2 min read

All primitives in JS are available in TS.

type Props = {
  size: number;
  name: string;
  disabled: boolean;
};

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.

type Props = {
  emptyObject: {};
  product: {
    id: string;
    price: number;
  };
};

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

type ListProps = {
  items: string[];
};

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

type ListProps = {
  items: {
    id: string;
    name: string;
    price: number;
  }[];
};

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

type Item = {
  id: string;
  name: string;
  price: number;
};

type ListProps = {
  item: Item;
  items: Item[];
};

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

type Button = {
  variant: "primary" | "danger" | "info";
  value: string | number;
};

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

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

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

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

I'm a software developer and a technical writer. On this blog, I write about my learnings in software development and technical writing.

Currently, working as a documentation lead at  Expo.