Last active
September 17, 2025 20:10
-
-
Save coderunner/372f2a4af8c64a00a126648976831192 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Type avec union | |
| type Status = 'active' | 'inactive' | null | |
| // Définition d'interfaces | |
| interface User { | |
| name: string; // propriété et type | |
| age: number; | |
| status: Status; | |
| } | |
| interface WithId { | |
| id: string | |
| } | |
| // Définition d'un objet | |
| const u1: User = {name: 'Anna', age: 33, status: 'active'} | |
| // accès aux propriétés | |
| u1.name | |
| u1['name'] | |
| // le compilateur nous aide | |
| u1.weight // le compilateur nous aide | |
| u1['weight'] | |
| u1.status = 'autre' | |
| // l'opérateur 'spread' insert une copie (superficielle) d'une objet | |
| const u2 = {...u1, name: 'Bob'} | |
| // ou tableau | |
| const u3: User & WithId = {...u2, id: '1'} | |
| const users: User[] = [u1, u2, u3] | |
| const clone = [...users] | |
| function printUsers(users: User[]): void { | |
| for (const u of users) { | |
| console.log(u); | |
| } | |
| } | |
| console.log('print user 1') | |
| printUsers(users) | |
| u2.age = 55; | |
| console.log('print user 2') | |
| printUsers(users) | |
| interface Incrementable { | |
| inc(): number | |
| } | |
| class Counter implements Incrementable { | |
| private _counter: number = 0 | |
| // un paramètre de constructeur private ou public est automatiquement un attribut | |
| // de la classe avec le même modificateur | |
| // ? pour un paramètre optionel, la valeur est undefined si non spécifié | |
| constructor(private _name: string, public quelquechose?: string, autrechose?: number) { | |
| } | |
| get counter() { | |
| return this._counter; | |
| } | |
| inc() { | |
| return this._counter++; | |
| } | |
| get name() { | |
| return this._name; | |
| } | |
| isZero(): boolean { | |
| if(this.counter === 0) { | |
| return true; | |
| } else { | |
| return false; | |
| } | |
| } | |
| toString() { | |
| // interpolation de chaîne de caractères avec ` ` et ${ } | |
| return `${this.name} : ${this.counter}` | |
| } | |
| } | |
| console.log('Counter') | |
| const c = new Counter('nom'); | |
| c._name | |
| c.quelquechose | |
| c.autrechose | |
| console.log(c.quelquechose) | |
| console.log(c.toString()) | |
| console.log(c.isZero()) | |
| c.inc() | |
| console.log(c.toString()) | |
| console.log(c.isZero()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment