Adloun

TypeScript : du JavaScript vérifié (école d'ingénieur) · Chapitre 4 · Exercice de TD

Compter les livres par rayon

Objets, interfaces et classes · niveau 1 (application)

Énoncé


import { LIVRES } from "../../catalogue.ts";

const parRayon: Record<string, number> = {};
for (const livre of LIVRES) {
  parRayon[livre.rayon] += 1;
}
console.log(parRayon);

tsc accepte ce programme. Qu'affiche-t-il ? Pourquoi tsc ne voit-il rien ? Le corriger, puis l'écrire avec une Map.

Corrigé

À la première rencontre d'un rayon, parRayon[rayon] vaut undefined, et undefined + 1 donne NaN :


$ npx tsc && node rayons.ts
{
  Informatique: NaN,
  'Mathématiques': NaN,
  Physique: NaN,
  'Littérature': NaN
}

Pour tsc, la lecture d'un Record<string, number> est un number, jamais undefined : il ne peut pas voir l'oubli. Corrections :


import { LIVRES } from "../catalogue.ts";

// Avec un Record : la clé absente se lit undefined, d'où ?? 0.
const parRayon: Record<string, number> = {};
for (const livre of LIVRES) {
  parRayon[livre.rayon] = (parRayon[livre.rayon] ?? 0) + 1;
}
console.log(parRayon);

// Avec une Map : get rend number | undefined, tsc oblige au test.
const compte = new Map<string, number>();
for (const { rayon } of LIVRES) {
  compte.set(rayon, (compte.get(rayon) ?? 0) + 1);
}
console.log(compte);

$ npx tsc && node exercices/ex5-rayons.ts
{ Informatique: 2, 'Mathématiques': 1, Physique: 1, 'Littérature': 2 }
Map(4) {
  'Informatique' => 2,
  'Mathématiques' => 1,
  'Physique' => 1,
  'Littérature' => 2
}

Exercices semblables

Le cours du chapitre · Tous les exercices du chapitre