Welcome back! I am Mihir, and in this lesson we will learn truthiness narrowing in TypeScript.
Truthiness narrowing happens when TypeScript narrows a type based on whether a value is treated as true or false in an if condition.
Basic Truthiness Narrowing
function printName(name: string | null) {
if (name) {
console.log(name.toUpperCase());
}
}Inside the if block, TypeScript knows name is not null.
Checking undefined
function greet(name?: string) {
if (name) {
return `Hello, ${name}`;
}
return "Hello, guest";
}Because name is optional, its type is:
string | undefinedThe if (name) check narrows it to string.
Falsy Values
JavaScript treats these values as falsy:
false0""nullundefinedNaN
This matters because truthiness checks can remove more than just null or undefined.
Common Mistake with Empty Strings
function formatTitle(title: string | null) {
if (title) {
return title.toUpperCase();
}
return "Untitled";
}This treats an empty string as missing.
formatTitle("");The result is:
"Untitled"That might not be what you want.
Safer Null Check
If you only want to remove null, check for null directly.
function formatTitle(title: string | null) {
if (title !== null) {
return title.toUpperCase();
}
return "Untitled";
}Now an empty string is still treated as a real string.
Checking null and undefined Together
function printValue(value: string | null | undefined) {
if (value != null) {
console.log(value.toUpperCase());
}
}value != null removes both null and undefined.
This is one place where loose inequality is intentionally useful.
Truthiness with Arrays
function printFirst(items: string[] | undefined) {
if (items) {
console.log(items[0]);
}
}This checks whether items exists, but it does not check whether the array has elements.
Better:
function printFirst(items: string[] | undefined) {
if (items && items.length > 0) {
console.log(items[0]);
}
}Quick Recap
- Truthiness narrowing uses conditions like
if (value). - It is useful for removing
nullandundefined. - Be careful with falsy values like
""and0. - Use direct checks when you need exact behavior.
value != nullremoves bothnullandundefined.
Next up, we will continue with Equality Narrowing →.