TypeScript : du JavaScript vérifié (école d'ingénieur) · Chapitre 7 · Application directe du cours
Trois réglages, trois verdicts
Outillage : modules, déclarations, Vite et tests · niveau 2
Énoncé
Le dossier erreurs/ex5-options a le tsconfig.json du projet et ce fichier :
import { LIVRES } from "./catalogue.ts";
const titres = LIVRES.map((l) => l.titre);
const [premier] = titres.toSorted();
console.log(premier.toUpperCase(), titres[5].length);
Prévoir la réponse de npx tsc --noEmit, puis la même commande avec --lib es2022,dom, puis avec --noUncheckedIndexedAccess. Qu'afficherait l'exécution ?
Corrigé
Avec le tsconfig.json du projet, rien à dire :
$ npx tsc --noEmit
Sans ES2023 dans lib, toSorted n'existe plus ; sur un tableau ordinaire (string[]), tsc propose la correction :
$ npx tsc --noEmit --lib es2022,dom
src/essai.ts:4:26 - error TS2550: Property 'toSorted' does not exist on type 'string[]'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2023' or later.
4 const [premier] = titres.toSorted();
~~~~~~~~
Found 1 error in src/essai.ts:4
Avec noUncheckedIndexedAccess, la déstructuration et l'indice 5 peuvent donner undefined :
$ npx tsc --noEmit --noUncheckedIndexedAccess
src/essai.ts:5:13 - error TS18048: 'premier' is possibly 'undefined'.
5 console.log(premier.toUpperCase(), titres[5].length);
~~~~~~~
src/essai.ts:5:36 - error TS2532: Object is possibly 'undefined'.
5 console.log(premier.toUpperCase(), titres[5].length);
~~~~~~~~~
Found 2 errors in the same file, starting at: src/essai.ts:5
Le catalogue a trois livres : premier existe, mais titres[5] vaut undefined, et l'exécution s'arrêterait sur une TypeError (« Cannot read properties of undefined »). Seule la troisième configuration l'a vu.
Exercices semblables
- Qui voit la faute corrigé
- Déclarer stockage.js corrigé
- Un délai venu de .env corrigé
- Ce que dit ESLint corrigé
- Migrer temps.js corrigé