Suggestion: error when using relational operators on types whose valueOf() method returns 'never' or 'void' #52773
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.
Activity
shicks commentedon Mar 1, 2023
We're investigating defining some opaque types for
bigintcompatibility shims:But today you can still write
wrap(123n) + 456and you won't get any complaint. If we had this, then we could make that an error, which would be great!RyanCavanaugh commentedon Mar 1, 2023
+is almost certainly doomed to permanent weirdness due toDate, unfortunately.justingrant commentedon Sep 29, 2023
On behalf of the Temporal champions, this proposal sounds great! 👍
The type of
Date.prototype.valueOfdoesn't have a type ofneverorvoid, so it wouldn't be affected by this proposal, right?I agree that
Datewill be forever weird for+and many other reasons, but this proposal seems like it could be a way to use the type checker to warn users that they are doing something that may fail at runtime. What I particularly like is that it allows the type author to opt into this behavior rather than hard-coding something just for some types likeTemporal.ZonedDateTime.What do you think?
justingrant commentedon Sep 29, 2023
Also, would this proposal would apply to not just
<and>but for all operators like+that also callvalueOf?