Disallow adding number and string #16895
Copy link
Copy link
Closed
Labels
Working as IntendedThe behavior described is the intended behavior; this is not a bugThe behavior described is the intended behavior; this is not a bug
Description
Or, why did you guys make the design decision to allow it?
1 + 2 // ok
1 + '2' // should be error
1 + [2] // error
1 + { a: 2 } // error
1 + (() => 2) // error
1 + Symbol(2) // error
1 + true // error
1 + undefined // error
1 + null // error
1 * 2 // ok
1 * '2' // error
1 * [2] // error
1 * { a: 2 } // error
1 * (() => 2) // error
1 * Symbol(2) // error
1 * true // error
1 * undefined // error
1 * null // errorIt would be better if this was an error, or at least an error behind a noImplicits flag which errored on operations that rely on implicit conversions, like TS already does for the most error-prone conversions.
As a side note, the error messages for + errors seem a bit more usable than those for * errors. Compare "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." (worse) with "Operator '+' cannot be applied to types '1' and 'number[]'." (better).
Apologies if this has been asked before - a search yielded hundred of results, and I didn't find anything in the first hundred or so.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
Working as IntendedThe behavior described is the intended behavior; this is not a bugThe behavior described is the intended behavior; this is not a bug
Activity
ajafff commentedon Jul 3, 2017
If you don't want to wait until this is implemented in the compiler, there's a rule in tslint that checks exactly this: https://palantir.github.io/tslint/rules/restrict-plus-operands/
rbuckton commentedon Aug 5, 2017
The pattern
1 + ''is fairly common for string interpolation and string conversion in JavaScript (and is generally faster in most host engines than(1).toString()orString(1)). This is because+is overloaded as both "arithmetic addition" and "string concatenation", while*is purely an arithmetic operator.As with Klaus Meinhardt (@ajafff)'s comment, if you require further restriction on the use of
+then a lint rule would be a better option.bcherny commentedon Aug 5, 2017
Bummer - I was hoping this would make it for the sake of consistently disallowing implicits. Allowing some and disallowing others is hard to explain to new TypeScriot users.