Truthiness and Null/Undefined Narrowing
12345678function 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"); } }
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.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Awesome!
Completion rate improved to 5.88
Truthiness and Null/Undefined Narrowing
Swipe to show menu
12345678function 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"); } }
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.
Thanks for your feedback!