Mastering TypeScript's Strict Null Checks: Best Practices for Safer Code
Learn how to use TypeScript's strict null checks feature to write safer, more reliable code by avoiding common null and undefined errors.
TypeScript is a powerful language that enhances JavaScript with static typing. One of its most valuable features is the ability to catch null and undefined errors at compile time using the strict null checks option. Enabling this feature helps you write more robust code by preventing runtime errors related to accessing or using null or undefined values.
By default, TypeScript allows variables to be null or undefined unless you explicitly disallow them. With strict null checks enabled, variables must be explicitly marked if they can hold null or undefined, reducing unexpected bugs.
Let's explore how to enable strict null checks and some best practices to handle null and undefined values safely in your TypeScript code.
### Enabling Strict Null Checks
To enable strict null checks, update your `tsconfig.json` file by setting the `strictNullChecks` option to `true`. This is often part of enabling the full `strict` mode.
{
"compilerOptions": {
"strictNullChecks": true,
// or simply enable all strict checks:
// "strict": true
}
}### Understanding Nullable Types
With strict null checks enabled, `null` and `undefined` are only assignable to variables explicitly declared to accept them. For example:
let name: string = "Alice";
// name = null; // Error: Type 'null' is not assignable to type 'string'.
let nullableName: string | null = "Bob";
nullableName = null; // OK### Best Practices for Safer Code
1. **Use union types to explicitly declare nullable variables.** When a value can be null or undefined, declare it clearly using `| null` or `| undefined`. This makes your code intention clear.
typescript function greet(name: string | null) { if (name === null) { console.log("Hello, guest!"); } else { console.log(`Hello, ${name}!`); } }
2. **Use type guards to check for null or undefined before using variables.** This ensures safe access and prevents runtime errors.
typescript function printLength(str: string | undefined) { if (str !== undefined) { console.log(str.length); } else { console.log("String is undefined"); } }
3. **Leverage the non-null assertion operator (`!`) only when you are sure a value is not null or undefined.** Use sparingly, as it tells TypeScript to ignore null checks and can introduce bugs if used improperly.
typescript let input: HTMLInputElement | null = document.querySelector('input'); // We assert input is not null because we are sure input exists. console.log(input!.value);
4. **Provide default values using the nullish coalescing operator (`??`).** This is helpful to handle null or undefined values gracefully.
typescript function getUsername(name: string | null | undefined) { // Use 'Guest' if name is null or undefined const displayName = name ?? "Guest"; console.log(`Welcome, ${displayName}`); }
### Conclusion
Using TypeScript's strict null checks helps you catch potential null or undefined errors during development, saving time debugging runtime issues. By explicitly declaring nullable types, using type guards, and safely handling values, you can write more predictable and safer TypeScript code.