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.
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Can you explain what "truthiness" means in TypeScript?
How does TypeScript handle other types in truthiness checks?
Can you show more examples of type narrowing in TypeScript?
Awesome!
Completion rate improved to 5.88
Truthiness and Null/Undefined Narrowing
Deslize para mostrar o 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.
Obrigado pelo seu feedback!