0
0
Typescriptprogramming~5 mins

Null and undefined types in Typescript

Choose your learning style9 modes available
Introduction

Null and undefined represent missing or empty values in TypeScript. They help us handle cases where a value might not exist yet.

When a variable might not have a value assigned yet.
When a function might return no result.
When you want to explicitly say a value is empty or missing.
When checking if a value exists before using it.
When handling optional data from users or APIs.
Syntax
Typescript
let value: null;
let value2: undefined;

let maybeNumber: number | null | undefined;

null means a variable has no value.

undefined means a variable has not been assigned a value yet.

Examples
This variable can only be null.
Typescript
let emptyValue: null = null;
This variable can only be undefined.
Typescript
let notAssigned: undefined = undefined;
This variable can hold a number, or be null, or undefined.
Typescript
let optionalNumber: number | null | undefined = null;
optionalNumber = 5;
optionalNumber = undefined;
Sample Program

This program shows how to check if a value is null, undefined, or a string, then prints the length if it is a string.

Typescript
function printLength(text: string | null | undefined) {
  if (text === null) {
    console.log('Text is null');
  } else if (text === undefined) {
    console.log('Text is undefined');
  } else {
    console.log(`Text length is ${text.length}`);
  }
}

printLength(null);
printLength(undefined);
printLength('hello');
OutputSuccess
Important Notes

Use strict equality === to check for null or undefined.

By default, null and undefined are different types in TypeScript.

You can allow variables to hold these types by using union types like string | null | undefined.

Summary

Null means a variable has no value.

Undefined means a variable has not been assigned a value yet.

Use union types to allow variables to hold null or undefined.