When using the +/- operator with strings and numbers.
There are many traps here, and things can go wrong.
e.g.
let result = '5' + 3;
console.log(result); // '53' - String concatenation
let result = '5' - 3;
console.log(result); // 2 - The string is converted to a number
result = 3 + '5';
console.log(result); // '35' - Still string concatenation
let result = '10' - 3;
console.log(result); // 7 - The string '10' is converted to the number 10
result = '5' - '2';
console.log(result); // 3 - Both strings are converted to numbers and then subtracted
I know, no one would write code like this in the real world
But there will be the following situation
function foo() {
// ...other logic
return "5"
}
// ... other logic
const bar = foo() + 5 // β
We should check that left and right expression are of the same type to avoid implicit conversion.
It is feasible when we can infer its type, skip check when found any
/unknown
/never
.
There is no possibility of false positives
Plus operator:
const foo = "5" // numberic
// ... other logic
const bar = foo + 5 // β
function foo() {
return "5"
}
// ... other logic
const bar = foo() + 5 // β
Minus operator:
const foo = "10"
// ...other logic
const bar = foo - 5 // β
Type Annotation:
let foo: string
// ...other logic
const bar = foo - 5 // β
let foo = (): string => {}
// ...other logic
const bar = foo() - 5 // β
function foo (bar: string) {
bar - 5 // β
}
const foo = "5"
// ... other logic
const bar = Number(foo) + 5 // β
function foo() {
return "5"
}
// ... other logic
const bar = Number(foo()) + 5 // β
Minus operator:
const foo = "10"
// ...other logic
const bar = Number(foo) - 5 // β
no-implicit-conversion
No response
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too