TS Null

Null & Undefined

In JavaScript, null and undefined are incredibly common causes of fatal runtime errors.

TypeScript provides excellent tools to safely handle these empty values.

By enabling strict null checks, the compiler forces you to handle missing data properly.

This single feature has saved developers countless hours of frustrating debugging.


1. Null vs Undefined

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

null is an intentional assignment representing absolutely nothing.

TypeScript treats both of them as distinct types that must be strictly handled.

Basic Null Example:

let emptyValue: null = null;
let notAssigned: undefined = undefined;

// You generally use union types for properties that might be empty let userName: string | null = null;

console.log("Values:", emptyValue, notAssigned, userName);


2. Non-Null Assertion Operator

Sometimes you know for an absolute fact that a value is not null, but TypeScript disagrees.

You can use the exclamation mark ! to assert that the value definitely exists.

This is called the non-null assertion operator, and it forces the compiler to trust you.

Assertion Example:

function getLength(text: string | null) {
  // We promise text is not null here!
  console.log(text!.length);
}

getLength("TypeScript is awesome!");

// Dangerous if you are wrong, but occasionally necessary.


3. SEO and Error Prevention

"Cannot read properties of undefined" is the most notorious error in web development.

When this error crashes a page, search engines might penalize your site's quality score.

Strict null checking is the ultimate defense mechanism for preserving uptime.

Optional Chaining Example:

type User = { profile?: { bio: string } };
const u: User = {};

// Safely accesses nested properties without crashing console.log(u.profile?.bio);


Exercise

?

Which symbol represents the Non-Null Assertion operator in TypeScript?


4. Final Thoughts

Always leave strictNullChecks turned on in your compiler configuration settings.

It will force you to write safer code and utilize optional chaining appropriately.

Next, we'll see how to add types to existing JavaScript libraries using DefinitelyTyped!