TSTypeScript
IntermediateLesson 10 of 15

Strict Mode & Null Safety – TypeScript

Why strict: true is a must and how to handle null and unknown safely.

With "strict": true in tsconfig.json you switch on several strict checks at once – including strictNullChecks (no null/undefined without permission) and noImplicitAny. New projects should always start out strict.

const name: string = "Ada";
// const leer: string = null;         // Error with strictNullChecks

function finde(liste: string[], gesucht: string): string | undefined {
  return liste.find((x) => x === gesucht);
}
const treffer = finde(["a", "b"], "b");
// console.log(treffer.toUpperCase());   // Error: 'treffer' is possibly 'undefined'
if (treffer !== undefined) {
  console.log(treffer.toUpperCase());
}
console.log(treffer?.toUpperCase() ?? "not found");

Two tools for exceptional cases: the type assertion as and the non-null assertion !. Both tell the compiler "trust me" – without a runtime check:

const eingabe = document.querySelector("#name") as HTMLInputElement | null;

const wert = eingabe!.value;             // ! : "is not null" – crashes if it is after all

const daten = JSON.parse('{"a":1}') as { a: number };   // Careful: unchecked!

In catch the error has type unknown with strict – you have to narrow it before you use it. noUncheckedIndexedAccess is also worthwhile: index accesses then return T | undefined.

try {
  JSON.parse("{kaputt");
} catch (e) {
  if (e instanceof Error) {
    console.log(e.name, e.message);
  } else {
    console.log("Unknown error", e);
  }
}

const liste: number[] = [1, 2, 3];
const x = liste[5];            // with noUncheckedIndexedAccess: number | undefined
WarningTreat as and ! like any: they move the error from compile time to runtime. For data from outside (API, JSON, forms) proper validation is needed, e.g. with a type guard or a library such as Zod.
TipRecommended additional options: noUncheckedIndexedAccess, noImplicitOverride, exactOptionalPropertyTypes (strict) and noFallthroughCasesInSwitch. In practice you start with strict and add more step by step.