#dev #atelier #typescript
- Introduction
- Pourquoi Typescript ?
- Les types de base
- Les types avancés
- Les types génériques
- TypeScript + React = <3
En JavaScript, les variables peuvent contenir n’importe quoi. Une même variable peut donc être et devenir :
let myVar = 'hello';
myVar = 3 *// no problem*
console.log(myVar) *// -> 3*
Cela ne pose pas de problème dans un contexte restreint, mais lorsqu’une application grandit, cela peut poser des problèmes où les impacts peuvent se répercuter beaucoup plus loin.
Pour citer Wikipédia :
TypeScript est un langage de programmation libre et open source développé par Microsoft qui a pour but d’améliorer et de sécuriser la production de code JavaScript
Nous assurons une robustesse au code en y indiquant un système de typage sur les variables, les fonctions, les classes, etc.
Les types de base en TypeScript sont :
type | utilité | exemple |
---|---|---|
string |
Représente du texte | const myVar: string = « Hello » |
number |
Représente un nombre | const myVar: number = 3 |
boolean |
Représente un booléen | const myVar: boolean = true |
array |
Représente un tableau | const myVar: number[] = [1, 2] |
tuple |
Représente un tableau où les éléments sont connus, mais différents | const myVar: [number, string] = [123, « nous irons au bois] |
any |
Représente n’importe quel type. La majorité du temps, on n’en a pas besoin… | const myVar: any = { ‘123’: 456 } |
void |
Représente l’inverse de any . Ne renvoie rien |
function myFn (): void { console.log(‘ |
- Intersection (&)
interface GenericItem {
'@id': string;
name: string;
description: string;
}
interface GenericSalable {
priceTI: number;
articleId: number;
}
interface Product extends GenericItem, GenericSalable {
offerId: number;
}
/* OR
type Product = GenericItem & GenericSalable & {
offerId: number;
}
*/
/*
* Results to :
* {
* @id': string;
* name: string;
* description: string;
* priceTI: number;
* articleId: number;
* offerId: number;
* }
*/
- Union (|)
type MyNumber = number;
type MyString = string;
type MyText = MyNumber | MyString;
const myText: MyText = 12;
const myText: MyText = '12';
const myText: MyText = false; // throws an error
- keyof
const myObjectBase = {
'@id': '/zbra/123',
name: 'Zbra'
}
const myObject: keyof typeof myObjectBase = '@id';
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
let x = { a: 1, b: 2, c: 3, d: 4 };
getProperty(x, "a"); // okay
getProperty(x, "m"); // error: Argument of type 'm' isn't assignable to 'a' | 'b' | 'c' | 'd'.
- record
const myObject: Record<string, number> = { test: 123 };
const myObject: Record<string, number> = { test: 'Oops' }; // throws an error since 'Oops' is not of type 'number'
- object
const myObject: {
'@id': string;
[key: string]: string;
} = {
'@id': 'test',
hello: 'world'
}
function doLogging <T>(arg: T): T {
console.log("I'm logging...");
return arg;
}
check file at ./complex-typescript.tsx