Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте 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

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 3

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Awesome!

Completion rate improved to 5.88

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

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 3
some-alt