Typescript
Subtlety: Typescript is a superset of JavaScript.
It allows you to add types to variables, functions, etc.
It is then transpiled into JavaScript for use in a browser or server.
Resources
https://www.typescriptlang.org/docs/
Common types
https://www.typescriptlang.org/docs/handbook/2/everyday-types.html
To do / To avoid
https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html
To study
-
type of union/intersection
-
Type called "literal" (for types with precise values "yes/no")
-
enums (example type with precise values, top, bottom, left, right)
-
The scope of the elements (public, private, protected (private but accessible by subclasses))
-
creating your own mixed types (aliases)
JavaScript code vs typescript code
Context: We want a decision generator so that most of the time our algorithm tells us to go to work.
In Javascript
function shouldWorkToday() {
const randomNumber = Math.random(); // genere entre 0 et 1
return randomNumber > 0.2;
}
const workToday = shouldWorkToday();
console.log(workToday ? "Oui, il faut travailler aujourd'hui." : "Non, pas besoin de travailler aujourd'hui.");
In Typescript
// Ajout du type boolean
function shouldWorkToday(): boolean {
// ajout du type number
const randomNumber: number = Math.random();
return randomNumber > 0.2;
}
// Ajout du type boolean
const workToday: boolean = shouldWorkToday();
console.log(workToday ? "Oui, il faut travailler aujourd'hui." : "Non, pas besoin de travailler aujourd'hui.");