- Mastering TypeScript 3
- Nathan Rozentals
- 250字
- 2021-07-02 12:42:47
Null operands
TypeScript will also check for null or undefined values when we use basic operands, such as addition, multiplication, less than, modulus, and power of. This can best be seen by using a simple example, as follows:
function testNullOperands(arg1: number, arg2: number | null | undefined) { let a = arg1 + arg2; let b = arg1 * arg2; let c = arg1 < arg2; }
Here, we have defined a function named testNullOperands that takes two arguments, arg1 and arg2, which can either be number, null, or undefined. Attempting to compile this code will result in a number of errors, as follows:
(92,20): error TS2533: Object is possibly 'null' or 'undefined' (93,20): error TS2533: Object is possibly 'null' or 'undefined' (94,20): error TS2533: Object is possibly 'null' or 'undefined'
TypeScript has generated an error for all three of our attempted computations. This is a very powerful extra source of type checking, and the key to these errors is that the argument arg2 may be a valid number, or it may be null or undefined. The addition operator (+) will not allow us to attempt adding null to a number, nor will it allow us to add undefined to a number, hence the first error. The multiplication operator (*) and the less than operator (<) have the same constraints, which are generating the second and third errors.
TypeScript will detect where we are using operands, and ensure that both sides of the operands are valid numbers.