Truthiness narrowing helps TypeScript understand if a value is true or false in simple checks. This lets the program know what type the value really is inside conditions.
0
0
Truthiness narrowing in Typescript
Introduction
When you want to check if a variable is not null or undefined before using it.
When you want to run code only if a string is not empty.
When you want to make sure a number is not zero before doing math with it.
When you want to confirm an object exists before accessing its properties.
Syntax
Typescript
if (value) { // code here runs if value is truthy } else { // code here runs if value is falsy }
TypeScript narrows the type inside the if block to exclude null and undefined. For booleans, it also excludes false.
This helps avoid errors by making sure the value is usable inside the block.
Examples
This checks if
name is not null or empty before using it.Typescript
let name: string | null = "Alice"; if (name) { // name is treated as string here, not null console.log(name.toUpperCase()); }
This runs only if
count is truthy. TypeScript narrows it to number.Typescript
let count: number | undefined = 5; if (count) { // count is treated as number here, not undefined or zero console.log(count + 1); }
This shows how truthiness narrowing works with booleans and null.
Typescript
let flag: boolean | null = null; if (flag) { // runs only if flag is true console.log("Flag is true"); } else { console.log("Flag is false or null"); }
Sample Program
This program greets a person by name if given, or says "Hello, guest!" if the name is null.
Typescript
function greet(name: string | null) { if (name) { console.log(`Hello, ${name.toUpperCase()}!`); } else { console.log("Hello, guest!"); } } greet("Bob"); greet(null);
OutputSuccess
Important Notes
Falsy values in JavaScript and TypeScript include false, 0, '' (empty string), null, undefined, and NaN.
Truthiness narrowing helps avoid errors by making sure you only use values when they are valid.
Summary
Truthiness narrowing lets TypeScript know a value is valid inside if checks.
This helps prevent errors by narrowing types to exclude falsy values.
Use it to safely work with values that might be null, undefined, or empty.