Suggestion: stricter operators
See original GitHub issueCurrently operators like “+” are defined such that they match their semantics in JS. The below are all allowed by the compiler and produce the shown values, even with --strictNullChecks
on.
2 + 'a'
=>"2a"
null + 'a'
=>"nulla"
(!)2 - null
=>2
I propose letting users opt in (maybe via some --strictOperators
) to strict operator behavior. Concretely I think this means:
-
restrict
+
, and+=
to justnumber
andstring
, e.g. for the former only declarefunction +(a: number, b: number): number; function +(a: string, b: string): string;
-
restrict
-
and-=
to justnumber
(any
should continue to work as normal, of course.)
Relevant spec section: https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#419-binary-operators
See also “Expression operators” in the strictNullTypes
change: https://github.com/Microsoft/TypeScript/pull/7140
and in particular this rationale: https://github.com/Microsoft/TypeScript/pull/7140#issuecomment-186432250
This would fall under of “stricter” TypeScript, https://github.com/Microsoft/TypeScript/issues/274 .
Issue Analytics
- State:
- Created 7 years ago
- Reactions:15
- Comments:14 (10 by maintainers)
number + string is actually quite common in JavaScript land and will probably not happen as it moves the
convenience - type safety
slider too much towards safety.null + string should be disabled as a part of
strictNullChecks
.Note:
A number of
wat
things are disabled in TypeScript e.g.[] + []
(valid JavaScript, produces “”) is an error in TypeScript. Similarly"hello" + 1
is allowed (like I mentioned) but"hello" - 1
is an error 🌹@basarat I really struggle when the argument “because that’s how Javascript does it” is applied. Particularly in cases like this where I think the cognitive load on the developer is increased by decisions to stick to the Javascript way. Not because it’s unclear how
+
behaves, rather that is creates cognitive dissonance with the rest of the type system:I understand that
+
is defined by the spec to work on combinations ofnumber
andstring
and so has well-defined behaviour, but given the example above I think it’s more confusing than useful for it to have been defined in this way (the Javascript way). Particularly when explicit conversion is so simple and more readable.