Description
Suggestion
π Search Terms
valueof never
β Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- (This would be a breaking change inasmuch as it will generate additional errors.)
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
- (I hope so!)
β Suggestion
At runtime, each operand of a relational operator is converted to a primitive value if needed by calling its valueOf()
method (among other things). A type can be made effectively incomparable by giving it a valueOf
method that throws an exception.
Ideally, tsc
would check the valueOf
signature of each operand, and produce a type error for any relational expression that implicitly invokes a valueOf
whose declared return type is never
or void
.
π Motivating Example
The following code unconditionally throws at runtime and passes type-checking.
class C {
valueOf() {
throw new Error("Please don't call me again!")
}
}
const a = new C();
const b = new C();
if (a < b) { // <- No error
console.log("I am unreachable");
}
π» Use Cases
TC39 Temporal PlainDate
and Instant
types throw an exception when compared this way (for reasonable reasons). It's easy to accidentally write code that naively compares these types using an operator instead of the appropriate compare
method. It would be ideal if this was caught statically.