Skip to content

Suggestion: error when using relational operators on types whose valueOf() method returns 'never' or 'void'Β #52773

Open
@yseymour

Description

@yseymour

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");
}

Playground link

πŸ’» 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions