Typescript - Truthiness
What is truthiness?
Truthiness is a term coined by comedian Stephen Colbert to describe something that feels true, even if it is not based on facts or logic. In programming, truthiness refers to how a value is evaluated in a boolean context, such as an if statement or a logical operator.
In TypeScript, a value is either truthy or falsy, depending on whether it is considered equivalent to true or false. The following values are falsy in TypeScript:
All other values are truthy, including:
Why does truthiness matter?
Truthiness can lead to unexpected results and bugs when working with TypeScript. For example, consider the following code snippet:
let name = "";
if (name) {
console.log("Hello, " + name);
} else {
console.log("Please enter your name");
}
You might expect this code to print “Please enter your name” if the name variable is an empty string. However, since an empty string is falsy, the else branch is executed, and the code prints "Hello, " instead.
Another common source of confusion is the use of logical operators, such as &&, ||, and !. These operators do not always return a boolean value, but rather the value of the last operand that determines the outcome of the expression. For example:
let x = 0;
let y = 1;
let z = x || y; // z is 1, not true
let w = x && y; // w is 0, not false
let v = !x; // v is true
In the above example, x || y returns y because x is falsy, and x && y returns x because x is falsy. Only the ! operator returns a boolean value by negating the truthiness of its operand.
领英推荐
How to avoid truthiness pitfalls?
There are some best practices and tools that can help you avoid the pitfalls of truthiness in TypeScript. Here are some of them:
0 == false; // true
0 === false; // false
"1" == 1; // true
"1" === 1; // false
null == undefined; // true
null === undefined; // false
let name = "";
let hasName = Boolean(name); // false
let hasName = !!name; // false
function greet(name: string | undefined) {
if (name) {
// name is string
console.log("Hello, " + name);
} else {
// name is undefined
console.log("Please enter your name");
}
}
Conclusion
Truthiness is a concept that can cause confusion and errors when working with TypeScript. By understanding how truthiness works, and by following some best practices and tools, you can write more reliable and maintainable TypeScript code.