TypeScript Null-Safety
TypeScript null-safety overview
// Without strict null checks (default behavior): let name: string = null; // No error // With strict null checks: let name: string = null; // Error: Type 'null' is not assignable to type 'string'.let name: string | null = null; // Nullable type let age: number | undefined = undefined; // Nullable type let count: number = 5; // Non-nullable typefunction greet(name?: string) { // ... } interface Person { name?: string; age?: number; }let element: HTMLElement | null = document.getElementById('myElement'); let value: string = element!.innerText; // Non-null assertionclass Example { name!: string; // Definite assignment assertion }function isNonNull(value: string | null): value is string { return value !== null; } let input: string | null = // ...; if (isNonNull(input)) { // input is string here }
Last updated