TypeScript Null-Safety
TypeScript null-safety overview
Here are some key aspects of null-safety in TypeScript:
Strict Null Checks: TypeScript introduced strict null checks, which means that by default, variables cannot be assigned the value of
nullorundefinedunless explicitly specified. If you try to assign or use a variable that might benullorundefined, TypeScript will generate a compilation error.// 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'.Nullable and Non-Nullable Types: TypeScript allows you to explicitly define whether a variable can be
nullorundefinedby using the union type withnullorundefined.let name: string | null = null; // Nullable type let age: number | undefined = undefined; // Nullable type let count: number = 5; // Non-nullable typeOptional Parameters and Properties: You can use the
?modifier for function parameters and object properties to indicate that they are optional and can beundefined.function greet(name?: string) { // ... } interface Person { name?: string; age?: number; }Non-Null Assertion Operator (
!): TypeScript provides the non-null assertion operator (!), which tells the compiler to consider a value as non-null even if TypeScript's type system can't guarantee it. This should be used with caution because it might lead to runtime errors if the value is, in fact,nullorundefined.let element: HTMLElement | null = document.getElementById('myElement'); let value: string = element!.innerText; // Non-null assertionStrict Property Initialisation: When using the
strictPropertyInitializationflag, TypeScript ensures that class properties are initialised in the constructor or have a definite assignment assertion (!).class Example { name!: string; // Definite assignment assertion }Type Guard Functions: Type guards are functions that help narrow down the type of a variable within a certain code block. For example, checking if a variable is not
nullbefore using it.function isNonNull(value: string | null): value is string { return value !== null; } let input: string | null = // ...; if (isNonNull(input)) { // input is string here }
These features collectively contribute to a more robust null-safety mechanism in TypeScript, reducing the likelihood of null-related runtime errors. However, it's important for developers to understand and apply these features appropriately to ensure code correctness and safety.
Last updated