Background
Many statically typed languages (C++, C#, Python) allow explicit overload definitions for operators (e.g., +, -, *, ==) at the class level. In TypeScript, as in JavaScript, operator overloading is absent at the language level due to historical and architectural reasons.
Problem
When support for arithmetic or other operations is needed for complex types (e.g., complex numbers or vectors), it is impossible to change standard operators. This restricts expressiveness and requires inventing workarounds.
Solution
In TypeScript, operator overloading is simulated through specially named methods (e.g., add, equals, multiply). By equipping a class with such methods, we achieve type-safe behavior, although the syntax is not as concise as in C++.
Example code:
class Vector { constructor(public x: number, public y: number) {} add(other: Vector): Vector { return new Vector(this.x + other.x, this.y + other.y); } equals(other: Vector): boolean { return this.x === other.x && this.y === other.y; } } const a = new Vector(1, 2); const b = new Vector(3, 4); const c = a.add(b); // Vector { x: 4, y: 6 } const eq = a.equals(b); // false
Key features:
Can you override the behavior of the operator "==" or "+" for your own class in TypeScript?
No, JavaScript (and TypeScript) does not allow direct overloading of standard operators for user-defined objects. Operators are strictly applied according to the standard for Object, Number, and other primitives. Any attempt at such "overriding" will result in incorrect or unexpected behavior or simply won't work.
Can you use valueOf or toString to indirectly influence operators?
In some cases, you can use valueOf (for example, for brief conversion to a number), but only for operators that access the primitive value of the object.
class Box { constructor(private v: number) {} valueOf() { return this.v; } } const a = new Box(10); console.log(a + 5); // 15 — works, but for complex objects it is non-intuitive
However, for complex structures and logical operators, it makes sense to use explicit methods.
Are there plans to add operator overloading in TypeScript or ECMAScript?
At the moment, there are no approved plans: fundamentally, operator overloading contradicts the design of JS, as it can significantly change the behavior of standard objects and lead to code instability.
A developer creates a Matrix class where they implement valueOf/toString for substitution in mathematical expressions. Adding with numbers or strings yields unpredictable results, and strict typing is impossible.
Pros:
Cons:
The Vector class implements methods add, multiply, equals with clear typing of input and output parameters. Class clients explicitly use the corresponding methods, semantics are preserved, and strict typing is ensured.
Pros:
Cons: