In the previous part of this posts series, we discussed about safe nullability.
Now we will explain and solve the third and last problem of TypeScript default behavior: remains of dynamic typing.
We will cover:
TypeScript is supposed to be a "static type checker", as opposed to JavaScript in which typing is deeply dynamic.
But in a previous part of this post series, we also explained that TypeScript is built as a superset of JavaScript.
So the problem is: some parts of JavaScript dynamic typing system remain in TypeScript. We are thus going to explain how to suppress these remaining behaviors to achieve full static typing.
The best example of the problem is equality checks. In JavaScript, == is not exactly an equality check, but an equivalence check:
1 == "1"; // true
Despite the types being different, some conversion rules come into action so JavaScript is able to compare the values. It can lead to a lot of errors, because the rules details are difficult to remember, are sometimes quite weird, and are not exactly the same in all dynamic languages (like PHP for example).
These equivalence checks only makes sense in a dynamically typed language like JavaScript. From the moment we decide to work in TypeScript, only actual equality checks (type and value) should be used.
1 === "1"; // false
The eqeqeq lint rule enforces it.
People coming from languages like Java, C# or Rust should be particularly careful with this problem, as == in JavaScript or TypeScript does not mean the same as in these languages. In JavaScript and TypeScript, a third = is required to achieve the same behavior.
Think conditions are now safe? Unfortunately not, because conversions can be implicit:
let tax: number | undefined = 0; if (tax) { console.log("Process payment"); } if (!tax) { throw new Error(); }
The above example is equivalent to:
let tax: number | undefined = 0; if (tax == true) { console.log("Process payment"); } if (tax == false) { throw new Error(); }
As you can see, there were implicit ==, so conversions still happen: 0 is not equivalent to true, it is equivalent to false. So it will error despite tax being a valid value.
The strict-boolean-expressions lint rule disallows such implicit conditions, and enforces actual checks:
let tax: number | undefined = 0; if (tax !== undefined) { console.log("Process payment"); } if (tax === undefined) { throw new Error(); }
It may be one of the most tedious rule to follow for people used to quick conditions in JavaScript, but to put it into perspective, it is just the normal way to do things in other languages like Java, C# or Rust.
As shown in the configuration part, disabling allowNumber and allowString sub-options is important to avoid all errors.
The only exception allowed is for objects and arrays: these cases are safe because contrary to strings and numbers, they do not have falsy values. So the following is still OK:
let movie: Movie | undefined; if (movie) {} if (!movie) {}
Note: switch statements are already safe as they use === internally.
The strict-boolean-expressions lint rule takes care that conditions checks are type safe, but there are other conditions syntaxes than if:
const movieRating = userRating || 5; // Which is a shorter version of: const movieRating = userRating == true ? userRating : 5;
If the user rated 0, 0 is equivalent to false, so rating will be 5 instead of 0.
It can be avoided with modern JavaScript:
const movieRating = userRating ?? 5; // Which is a shorter version of: const movieRating = userRating !== undefined && userRating !== null ? userRating : 5;
It can be enforced by the prefer-nullish-coalescing lint rule.
Note that ?? should not be used everywhere: || is still relevant when working with booleans.
In JavaScript, the operator can be used both for mathematical addition of numbers, or strings concatenation. It leads to error.
"There is " 3 1 "Matrix movies"; // 31 "There is " (3 1) "Matrix movies"; // 4
The operator should be reserved for mathematical addition. Or at least, it should be used only with data of the same type, which the restrict-plus-operands lint rule enforces.
Template strings from modern JavaScript should be used for string concatenation, which the prefer-template lint rule enforces:
const movie = `Everything everywhere all at once`; `${movie} is the best movie!`;
Conversely, only strings should be used in template strings, which the restrict-template-expressions lint rule enforces.
If mixing types is what is actually wanted, conversions should be explicit:
const total = 3; `There is ${total.toFixed()} Matrix movies`;
Note that template strings can be nested:
const total = 3; `There is ${total.toFixed()} Matrix movie${total > 1 ? "s" : ""}`;
This is the end of this posts series. You can follow my account (button on top right of this page) to know when other posts about TypeScript or other topics like Angular are published.
You want to contact me? Instructions are available in the summary.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3