TASIOMIND.DEV — OPERATIONAL▸▸▸FULL STACK DEVELOPER @ GWQ SERVICEPLUS AG▸▸▸FOUNDER — K8SGPT.AI▸▸▸OPEN SOURCE: ACTIVE▸▸▸DISTRIBUTED SYSTEMS / KUBERNETES / AI▸▸▸RUST + GO + PYTHON▸▸▸FIELD TESTED / STATUS — NOMINAL▸▸▸LOCATION: EUROPE/BERLIN▸▸▸TASIOMIND.DEV — OPERATIONAL▸▸▸FULL STACK DEVELOPER @ GWQ SERVICEPLUS AG▸▸▸FOUNDER — K8SGPT.AI▸▸▸OPEN SOURCE: ACTIVE▸▸▸DISTRIBUTED SYSTEMS / KUBERNETES / AI▸▸▸RUST + GO + PYTHON▸▸▸FIELD TESTED / STATUS — NOMINAL▸▸▸LOCATION: EUROPE/BERLIN▸▸▸

Common Prop Types in TypeScript and React

June 29, 2021

All primitives in JS are available in TS.

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

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

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

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

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

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

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

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

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

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