Rer
Rer
make sense of them, and then choose their branches depending on whether the result
is true or false. Values like
0
NaN
"" (the empty string)
0n (the bigint version of zero)
null
undefined
all coerce to false, and other values get coerced to true. You can always coerce
values to booleans by running them through the Boolean function, or by using the
shorter double-Boolean negation. (The latter has the advantage that TypeScript
infers a narrow literal boolean type true, while inferring the first as type
boolean.)
TypeScript doesn’t hurt us here at all, but this behavior is worth noting if you’re
less familiar with JavaScript. TypeScript can often help you catch bugs early on,
but if you choose to do nothing with a value, there’s only so much that it can do
without being overly prescriptive. If you want, you can make sure you handle
situations like these with a linter.
One last word on narrowing by truthiness is that Boolean negations with ! filter
out from negated branches.
function multiplyAll(
values: number[] | undefined,
factor: number
): number[] | undefined {
if (!values) {
return values;
} else {
return values.map((x) => x * factor);
}
}