Beginner's TypeScript #21


Error Message: “X is Possibly Null Or Undefined”

We start by declaring a variable searchParams that is initialized with the URLSearchParams class instance:

const searchParams = new URLSearchParams(window.location.search);

This object permits us to invoke the get method, which retrieves the id parameter. The get method can return string or null:

const id = searchParams.get("id");

When we attempt to log the id to the console, we get an error:

console.log(id.toUpperCase()); // red squiggly line under id

The error message reads:

// hovering over id shows:
'id' is possibly 'null'.

TypeScript is telling us that id could be null.

We will determine why this error is happening and how to fix it.

👉 Solutions

The id we are getting from searchParams.get(“id”) could either be a string or null:

const searchParams = new URLSearchParams(window.location.search);
const id = searchParams.get("id");

// hovering over `id` shows:
const id: string | null;

If we try to call toUpperCase() on a null value, we will encounter a runtime error. This is not a good situation, and TypeScript’s error is useful in warning us about this potential issue.

console.log(id.toUpperCase()); // This will throw a runtime error if id is null

There are several ways to address this error:

1️⃣ Optional Chaining

The first technique is to use optional chaining, represented by the ?. operator:

const result = id?.toUpperCase();

This tells TypeScript to call toUpperCase() on id if id exists. If ID is null, the function will return undefined.

This method does not guarantee that result will be a string, but it will prevent the runtime error.

2️⃣ Unsafe Non-nullable Assertion

Another option is to use the ! operator to assert that id is not null:

console.log(id!.toUpperCase());

The ! operator doesn’t do anything at runtime and is only used for TypeScript’s type checking.

However, this is generally not a good idea because if id is indeed null, you will encounter the same runtime error as before.

3️⃣ Type Narrowing

A better option is to conduct type narrowing by checking if id exists before calling toUpperCase():

If id does exist, TypeScript will treat id within the narrowing block as a string:

if (id) {
  console.log(id.toUpperCase());
}

// hovering over `id` inside the `if` block shows:
const id: string;

Alternatively, you can use a typeof check to verify if id is a string:

if (typeof id === "string") {
  console.log(id.toUpperCase());
}

I hope you found it useful. Thanks for reading. 🙏

Let’s get connected! You can find me on: