Chapters - Table of contents →
You will find below a summary of all the essential knowledge to get started with TypeScript.
Scalars
TypeScript provides 6 main scalar types: string, number, boolean, bigint, null, and undefined.
Strings can also be typed as literals (const name: 'John' = "John") and any type can be transformed as an array by adding a [] prefix to the type definition.
Finally, you can assign multiple types to a variable by using the | operator.
1const name: string = 'John'
2const names: string[] = ['John']
3const zipCode: string | number = 75000
4
5// remember, all type include `null` and `undefined`
6const name: string = null
7
Objects
Objects type can be defined using the interface keyword:
1interface ButtonProps {
2 type: "primary" | "secondary";
3 size: "small" | "medium" | "large";
4 classNames: string[];
5 name: string;
6 label?: string;
7 disabled?: boolean;
8 loading?: boolean; // adding a loading state to `<Button />`
9}
10
Remember, you can extract common types properties in common types that they will extend:
1interface ThemableComponentProps {
2 type: "primary" | "secondary";
3 size: "small" | "medium" | "large";
4 classNames: string[];
5}
6
7interface FormComponentProps {
8 name: string;
9 label?: string;
10 disabled?: boolean;
11}
12
13interface ButtonProps extends ThemableComponentProps, FormComponentProps {
14 loading?: boolean; // adding a loading state to `<Button />`
15}
16
Remember, unlike variables, object properties' types do not contain null and undefined.
Functions: React components and hooks
TypeScript and React are well integrated in order to provide consistent JSX typing.
General DOM elements, such as <div> (called intrinsic elements) are typed by React.
React components and especially their props types are automatically inferred by TypeScript.
Both React components and custom hooks are function that requires arguments types and a return type, as follows:
1interface ButtonProps extends ThemableComponentProps, FormComponentProps {
2 loading?: boolean // adding a loading state to `<Button />`
3}
4
5const Button = ({ name }: ButtonProps): JSX.Element => {
6 // ...
7}
8
ℹ️ When it comes to React components, the JSX.Element return type can be omitted.
Caution, the typing of function in object properties is slightly different at the return type level:
1interface ButtonProps extends ThemableComponentProps, FormComponentProps {
2 loading?: boolean;
3 // our onClick callback props
4 onClick: () => void
5 // ^ not ":" but "=>"
6}
7