Common Prop Types in TypeScript and React
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};67type 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 type3 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