Typescript: Operator Overloads

Created on 26 Oct 2015  路  3Comments  路  Source: microsoft/TypeScript

It would simplify a lot of use cases if we could override relational, equality, additive, and Multiplicative operators.

My initial thoughts on how this would work is that functions would replace the operators with functions when compiling to JavaScript.

class MyClass {
    constructor() {
    }

    public Operator > (value: any):boolean {
        // compare value
    }
}

var myClass = new MyClass();

if(myClass > otherValue){
    // Do stuff
}

Becomes:

var MyClass = (function () {
    function MyClass() {
    }
    MyClass.prototype.greaterThan = function (value) {
        // compare value
    };
    return MyClass;
})();
var myClass = new MyClass();
if (myClass.greaterThan(otherValue) {
    // do Stuff
}
Declined Duplicate Out of Scope

Most helpful comment

i have written an ORM framework in typescript. Its still new and only supports mysql currently. Its architecture is based on entity framework.
https://www.npmjs.com/package/es-entity
Enabling Operator Overloading will support the creating of 'LINQ' like queries.
You can add this feature as a optional extension like Decorators feature with experimental implementation and compiler option. Hope to see this in typescript.

All 3 comments

One thing we avoid doing is type-driven emit. The idea is that TypeScript types have no bearing at runtime - the code is as close to the analogous JavaScript that you would have written. Given that, substituting in a method call for an operator would go against that.

Apart from that, this is related to #2319, so I'm going to close this as a duplicate.

i have written an ORM framework in typescript. Its still new and only supports mysql currently. Its architecture is based on entity framework.
https://www.npmjs.com/package/es-entity
Enabling Operator Overloading will support the creating of 'LINQ' like queries.
You can add this feature as a optional extension like Decorators feature with experimental implementation and compiler option. Hope to see this in typescript.

I'm developing numpy like library in typescript (bluemath). Operator overloading will significantly improve the interface of my NDArray class.

Was this page helpful?
0 / 5 - 0 ratings