Adloun

TypeScript : du JavaScript vérifié (école d'ingénieur) · Chapitre 2 · Application directe du cours

Absence : accepté ou refusé

Types de base et inférence · niveau 1 (application)

Énoncé

Pour chaque bloc a à f, dire si tsc l'accepte. Pour le bloc accepté qui pose pourtant problème à l'exécution, dire lequel et pourquoi.


const stocks = new Map([["9782956300014", 12]]);
const titres = ["Programmation Java", "Analyse MPSI"];

// a
const s1 = stocks.get("9782956300014") ?? 0;
const s2: number = s1 + 1;

// b
const s3: number = stocks.get("9782956300014") + 1;

// c
const t1: string = titres.find((t) => t.startsWith("A"));

// d
const t2 = titres.find((t) => t.startsWith("A"))?.length;
const t3: number = t2 ?? -1;

// e
let choix: string | undefined;
const t4: string = choix;

// f
const t5: string = titres[5];
console.log(s2, s3, t1, t3, t4, t5);
choix = "x";

Corrigé

a est accepté : ?? retire undefined, s1 est un number. b est refusé : on n'additionne pas un number | undefined. c est refusé : find peut ne rien trouver. d est accepté : ?. donne un number | undefined, que ?? complète. e est refusé : le type annoncé contient undefined. f est accepté : pour un tableau, tsc ne vérifie pas les indices (sans noUncheckedIndexedAccess), et titres[5] est un string… qui vaut undefined à l'exécution. C'est le bloc problématique.


$ npx tsc
null.ts:9:20 - error TS2532: Object is possibly 'undefined'.

9 const s3: number = stocks.get("9782956300014") + 1;
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~

null.ts:12:7 - error TS2322: Type 'string | undefined' is not assignable to type 'string'.
  Type 'undefined' is not assignable to type 'string'.

12 const t1: string = titres.find((t) => t.startsWith("A"));
         ~~

null.ts:20:7 - error TS2322: Type 'string | undefined' is not assignable to type 'string'.
  Type 'undefined' is not assignable to type 'string'.

20 const t4: string = choix;
         ~~


Found 3 errors in the same file, starting at: null.ts:9

Le bloc b donne TS2532 (« l'objet est peut-être undefined ») et non TS18048 : ce dernier nomme une variable, et stocks.get(…) n'en est pas une.

Exercices semblables

Le cours du chapitre · Tous les exercices du chapitre