Truthiness narrowing
In JavaScript we can use certain operator to check the truthiness of a value. Operators like if
, &&
, !
, ||
etc..
These constructs will coerce the value of their condition to check for truthiness, even if the value is not a boolean. Consider:
ts
letx = "Everyday"; // x is a string not a booleanif (x ) {console .log (true);}// logs true
Values like
0
NaN
""
(the empty string)0n
(thebigint
version of zero)null
undefined
all coerce to false
, and other values get coerced to true
.
We can check for this truthiness and use it as a type guard when writing our functions.
Let's see an example:
ts
functionprintLength (str : string | null) {'str' is possibly 'null'.18047'str' is possibly 'null'.console .log (. str length );}
Typescript will warn us that str
is possibly null, based on our declaration. We can fix this by checking for the truthiness of the value before proceeding:
ts
functionprintLength (str : string | null) {if (str ) {console .log (str .length );}}printLength ("hello"); // 5
This is another form of type guard.
By checking if the value of str
was true we eliminated the null
type and now we can use string methods since TypeScript has narrowed down str
to a string
, since it is the only other possible value from our declaration.
Front-End Usage:
You may be already using this in your functions to check for null
elements before making changes:
ts
functionstyleElementById (elementId : string,color : string) {constelement =document .getElementById (elementId );if (element ) {// The element exists, so we can safely apply the styleelement .style .backgroundColor =color ;} else {// The element doesn't exist, so we handle this caseconsole .log (`Element with ID '${elementId }' not found.`);}}// Example usage:// Assuming an element with ID "header" exists in the HTMLstyleElementById ("header", "lightblue");// Assuming no element with ID "footer" exists in the HTMLstyleElementById ("footer", "lightgreen"); // Will log "Element with ID 'footer' not found."