Site icon JD Bots

How to Narrow a Type with an if Check in TypeScript

A card titled Narrow a Type with if, labelled TypeScript Basics, showing text.toUpperCase() failing because text is possibly null, an if (!text) check, and the output HELLO.

Narrow a Type with if: Check a value first, and TypeScript knows it’s there.

When a value can be null, TypeScript won’t let you use it as text or a number until you check it. After a check such as if (!text) return …;, TypeScript knows that text isn’t null below it. This is called narrowing.

Every command and output on this page is real, run with Node.js 26.13.1 and TypeScript 7.0.2 on macOS.

Syntax

Syntax

function name(value: Type | null) {
  if (!value) {
    return fallback;
  }

  // below the check, value is a Type
}

See Narrowing in the TypeScript handbook, under Truthiness narrowing.

Prerequisites

The Example

A shout function that turns text into capitals, but may be given null instead of text. The file is shout.ts.

Step 1: Write the Code

shout.ts

function shout(text: string | null) {
  return text.toUpperCase();
}

console.log(shout("hello"));

Step 2: Check It with tsc

Terminal

tsc --noEmit shout.ts

Output

shout.ts(2,10): error TS18047: 'text' is possibly 'null'.

text can be null, and null has no toUpperCase(), so tsc stops at line 2.

Step 3: Fix It

Check text first, and leave the function when it’s missing:

shout.ts

function shout(text: string | null) {
  if (!text) {
    return "Nothing to say";
  }

  return text.toUpperCase();
}

console.log(shout("hello"));
console.log(shout(null));

Step 4: Check It and Run It

Check it again. No output means tsc found no errors:

Terminal

tsc --noEmit shout.ts

Then run it:

Terminal

node shout.ts

Output

HELLO
Nothing to say

Below the check, TypeScript knows text is a string. The call with null took the early return.

Common Mistakes

MistakeWhat happensDo this instead
Silencing the error with text!tsc is quiet, but null still crashes at run time: TypeError: Cannot read properties of null (reading 'toUpperCase')Check the value with if
Checking with !text when empty text is a valid valueEmpty text is caught by the check tooCheck text === null instead

FAQ

Which checks narrow a type?

Truthiness checks like this one, typeof, ===, instanceof and in, among others. The TypeScript handbook’s Narrowing page goes through them.

Conclusion

Check a value that can be null before you use it. Below the check, TypeScript narrows its type, and the possibly null error is gone.

Additional Resources

TypeScript, Node.js and other names mentioned are trademarks of their respective owners.

Exit mobile version