Adloun

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

Le type à chaque ligne

Unions et rétrécissement · niveau 1 (application)

Énoncé

Donner le type de la variable affectée à chacune des constantes a à g, puis le vérifier avec tsc.


import type { LignePanier, Livre } from "../../types.ts";

function suivre(
  v: string | number | undefined,
  l: Livre | LignePanier,
  e: unknown,
) {
  if (v === undefined) {
    const a: never = v;
    return;
  }
  const b: never = v;
  if (typeof v === "number" && v > 0) {
    const c: never = v;
  }
  if ("auteur" in l) {
    const d: never = l;
  }
  if (typeof e === "object") {
    const f: never = e;
  }
  if (e instanceof Error) {
    const g: never = e;
  }
}
console.log(suivre);

Corrigé

a : undefined. b : string | number, car le return a écarté undefined pour la suite. c : number (le test v > 0 ne change pas le type). d : Livre, seul membre qui a un auteur. f : object | null, car typeof null vaut "object" : le test ne suffit pas à lire une propriété. g : Error.


$ npx tsc
types.ts:9:11 - error TS2322: Type 'undefined' is not assignable to type 'never'.

9     const a: never = v;
            ~

types.ts:12:9 - error TS2322: Type 'string | number' is not assignable to type 'never'.
  Type 'string' is not assignable to type 'never'.

12   const b: never = v;
           ~

types.ts:14:11 - error TS2322: Type 'number' is not assignable to type 'never'.

14     const c: never = v;
             ~

types.ts:17:11 - error TS2322: Type 'Livre' is not assignable to type 'never'.

17     const d: never = l;
             ~

types.ts:20:11 - error TS2322: Type 'object | null' is not assignable to type 'never'.
  Type 'null' is not assignable to type 'never'.

20     const f: never = e;
             ~

types.ts:23:11 - error TS2322: Type 'Error' is not assignable to type 'never'.

23     const g: never = e;
             ~


Found 6 errors in the same file, starting at: types.ts:9

Exercices semblables

Le cours du chapitre · Tous les exercices du chapitre