Skip to main content

Common Prop Types in TypeScript and React

Published:

2 min read

243 words

All primitives in JS are available in TS.

TypeScript
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.

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

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

TypeScript
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:

TypeScript
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:

TypeScript
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:

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

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

TypeScript
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:

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

Previous Post
How To Integrate Firebase Authentication With an Expo App
Next Post
Prop types in React and TypeScript