0
0
Typescriptprogramming~5 mins

Strict null checks and safety in Typescript

Choose your learning style9 modes available
Introduction

Strict null checks help catch mistakes where a value might be missing or empty. This keeps your program safe and avoids crashes.

When you want to make sure a variable always has a real value before using it.
When you want to avoid errors caused by trying to use null or undefined values.
When you want TypeScript to help you find places where a value might be missing.
When working with user input that might be empty or missing.
When you want clearer and safer code that is easier to understand.
Syntax
Typescript
{
  "compilerOptions": {
    "strictNullChecks": true
  }
}

// Example variable declaration
let name: string | null = null;

// Checking before use
if (name !== null) {
  console.log(name.toUpperCase());
}

Setting strictNullChecks to true makes TypeScript check for null and undefined values strictly.

You must check if a value is null or undefined before using it, or TypeScript will show an error.

Examples
This example shows a number that can be null. We check before adding 1.
Typescript
let age: number | null = null;
age = 25;
if (age !== null) {
  console.log(age + 1);
}
This function greets a person if the name exists, otherwise it greets a guest.
Typescript
function greet(name: string | undefined) {
  if (name) {
    console.log(`Hello, ${name}!`);
  } else {
    console.log("Hello, guest!");
  }
}
Trying to use data.length without checking causes an error with strict null checks.
Typescript
let data: string | null = null;
// Error if strictNullChecks is true:
// console.log(data.length);

// Correct way:
if (data !== null) {
  console.log(data.length);
}
Sample Program

This program prints the length of a string if it exists, or a message if it is null.

Typescript
function printLength(text: string | null) {
  if (text === null) {
    console.log("No text provided.");
  } else {
    console.log(`Length: ${text.length}`);
  }
}

printLength(null);
printLength("Hello");
OutputSuccess
Important Notes

Always check for null or undefined before using values when strict null checks are on.

You can use ! (non-null assertion) to tell TypeScript a value is not null, but use it carefully.

Strict null checks make your code safer and easier to maintain.

Summary

Strict null checks help prevent errors by forcing you to handle null and undefined values.

Use checks like if (value !== null) before using values that can be null.

This feature makes your TypeScript code more reliable and clear.