Documentation :
- https://create-react-app.dev/docs/adding-typescript
- https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/basic_type_example
Pour créer une application react utilisant typescript :
npx create-react-app my-app --template typescript
Exercice "Tasks"
Créer une application react ts :
npx create-react-app tasksts --template typescript
Le but est de créer une application qui gère l'ajout, la modification, la suppression et le classement des tâches.
Instructions :
- Créer des interfaces dans le répertoire src/interfaces
- Créer TaskInterface pour commencer
- Pour les props, je vous invite à créer des interfaces (PropsTaskInterface) qui héritent (extends) de TaskInterface
- Créer un répertoire src/mocks dans lequel vous créez un fichier tasks.json
- Créer un répertoire services dans lequel vous créez un fichier taskService.ts
- Dans taskService.ts, importer tasks.json et exporter une méthode loadTasks qui renvoit une promesse qui implémente l'interface TaskInterface
Liste des types classiques à utiliser avec TS + React :
cf : https://github.com/typescript-cheatsheets/react
type AppProps = {
message: string;
count: number;
disabled: boolean;
/** array of a type! */
names: string[];
/** string literals to specify exact string values, with a union type to join them together */
status: "waiting" | "success";
/** an object with known properties (but could have more at runtime) */
obj: {
id: string;
title: string;
};
/** array of objects! (common) */
objArr: {
id: string;
title: string;
}[];
/** any non-primitive value - can't access any properties (NOT COMMON but useful as placeholder) */
obj2: object;
/** an interface with no required properties - (NOT COMMON, except for things like `React.Component<{}, State>`) */
obj3: {};
/** a dict object with any number of properties of the same type */
dict1: {
[key: string]: MyTypeHere;
};
dict2: Record<string, MyTypeHere>; // equivalent to dict1
/** function that doesn't take or return anything (VERY COMMON) */
onClick: () => void;
/** function with named prop (VERY COMMON) */
onChange: (id: number) => void;
/** function type syntax that takes an event (VERY COMMON) */
onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
/** alternative function type syntax that takes an event (VERY COMMON) */
onClick(event: React.MouseEvent<HTMLButtonElement>): void;
/** any function as long as you don't invoke it (not recommended) */
onSomething: Function;
/** an optional prop (VERY COMMON!) */
optional?: OptionalType;
/** when passing down the state setter function returned by `useState` to a child component. `number` is an example, swap out with whatever the type of your state */
setState: React.Dispatch<React.SetStateAction<number>>;
};