Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Truthiness and Null/Undefined Narrowing | Type Guard Foundations
Error Handling and Type Guards in TypeScript

bookTruthiness and Null/Undefined Narrowing

12345678
function printLength(str: string | null | undefined) { if (str) { // TypeScript knows 'str' is a string here console.log("Length:", str.length); } else { console.log("No string provided"); } }
copy

TypeScript uses truthiness checks and explicit null or undefined checks to narrow types within your code. When you use a value in a conditionβ€”such as an if statementβ€”TypeScript analyzes the possible types and removes null and undefined if the value is checked for truthiness. This means that inside the block where a value is confirmed to be truthy, TypeScript treats it as a non-null, non-undefined type, allowing you to safely access its properties or methods. This narrowing is essential for writing safe code that avoids runtime errors, especially when dealing with values that may be optional or missing. By leveraging these checks, you can prevent issues like trying to read properties from null or undefined, which would otherwise cause your program to crash.

question mark

Which statement best describes how TypeScript narrows types using truthiness or null/undefined checks?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 1. ChapterΒ 3

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Awesome!

Completion rate improved to 5.88

bookTruthiness and Null/Undefined Narrowing

Swipe to show menu

12345678
function printLength(str: string | null | undefined) { if (str) { // TypeScript knows 'str' is a string here console.log("Length:", str.length); } else { console.log("No string provided"); } }
copy

TypeScript uses truthiness checks and explicit null or undefined checks to narrow types within your code. When you use a value in a conditionβ€”such as an if statementβ€”TypeScript analyzes the possible types and removes null and undefined if the value is checked for truthiness. This means that inside the block where a value is confirmed to be truthy, TypeScript treats it as a non-null, non-undefined type, allowing you to safely access its properties or methods. This narrowing is essential for writing safe code that avoids runtime errors, especially when dealing with values that may be optional or missing. By leveraging these checks, you can prevent issues like trying to read properties from null or undefined, which would otherwise cause your program to crash.

question mark

Which statement best describes how TypeScript narrows types using truthiness or null/undefined checks?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 1. ChapterΒ 3
some-alt