0
0
Typescriptprogramming~5 mins

NonNullable type in Typescript

Choose your learning style9 modes available
Introduction

The NonNullable type helps you remove null and undefined from a type. This makes sure your values are always real and not empty.

When you want to make sure a variable never holds <code>null</code> or <code>undefined</code>.
When you get data that might be empty but you want to work only with real values.
When you want to avoid errors caused by missing values in your program.
Syntax
Typescript
NonNullable<Type>

Type is the original type you want to clean up.

The result is a new type without null and undefined.

Examples
This removes null and undefined from the type, so CleanString is just string.
Typescript
type CleanString = NonNullable<string | null | undefined>;
OnlyNumber will be just number, no null.
Typescript
type NumberOrNull = number | null;
type OnlyNumber = NonNullable<NumberOrNull>;
DefiniteBoolean is just boolean, no undefined.
Typescript
type MaybeBoolean = boolean | undefined;
type DefiniteBoolean = NonNullable<MaybeBoolean>;
Sample Program

This program defines a function that only accepts strings without null or undefined. It prints the length of the string. Trying to pass null or undefined causes an error.

Typescript
type Input = string | null | undefined;

function printLength(value: NonNullable<Input>) {
  console.log(`Length is ${value.length}`);
}

printLength("hello");
// printLength(null); // Error: Argument of type 'null' is not assignable to parameter of type 'string'.
// printLength(undefined); // Error: Argument of type 'undefined' is not assignable to parameter of type 'string'.
OutputSuccess
Important Notes

NonNullable only removes null and undefined, other types stay the same.

This helps catch mistakes early by making sure values are always present.

Summary

NonNullable removes null and undefined from types.

Use it to make sure your variables always have real values.

It helps prevent errors caused by missing or empty values.