Skip to content Skip to sidebar Skip to footer

Typescript Arrow Operator To Define A Function On Prototype

As shown in this example, the assignment to a and defining b results in different function type. export module A { export class Test { constructor(){}

Solution 1:

The valid syntax for arrow functions is different from 'member location`. The "only" way to put functions on the prototype are via member function. Arrow function are actually member properties (which just happen to be functions). Your code is equivalent to the following:

exportmodule A {
    exportclassTest {
        constructor(){}               
        a = function (x){ returnMath.sin(x); }
        b (x) : any { returnMath.sin(x); }
    }
}

And member properties go on this not prototype.

What you can do is define it as a member function and then override it in the constructor:

exportmodule A {
    exportclassTest {
        constructor(){
            this.a =  (x)=>Math.sin(x);
        }               
        a (x){ }
        b (x) : any { returnMath.sin(x); }
    }   
}

Even put it on the prototype if you want :

classBase {
    constructor(){
        Base.prototype.a =  (x)=>Math.sin(x);
    }               
    a (x){}
} 

classChildextendsBase{
    constructor(){
        super();
    }

    a(x){returnsuper.a(x);}
}

var child = newChild();
console.log(child.a(Math.PI));

Solution 2:

What is wrong with just using a standard function ? i.e.

exportmodule A {
    exportclassTest {
        constructor(){}               
            a =(x) => { returnMath.sin(x); }
            b (x) : any { returnMath.sin(x); }
        c(x:number): number {
          returnMath.sin(x);
        }
    }
}

Post a Comment for "Typescript Arrow Operator To Define A Function On Prototype"