Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use TypeScript overloads when using fat arrow syntax for class methods?

I've converted some classes from the conventional form:

class TestOverloads {     private status = "blah";     public doStuff(selector: JQuery);     public doStuff(selector: string);     public doStuff(selector: any) {         alert(this.status);     } } 

to use arrow function expressions instead:

class TestOverloads2 {     private status = "blah";     public doStuff = (selector: any) => {         alert(this.status);     } } 

so as to avoid scoping problems when the class methods are used in a callback (see here for background).

I can't work out how to recreate my overloaded function signatures though. How would I write my overloads when using the fat arrow?

like image 444
Jonathan Moffatt Avatar asked Dec 17 '13 22:12

Jonathan Moffatt


People also ask

Can you overload methods in TypeScript?

In TypeScript, function overloading, or method overloading, is the ability to create multiple methods with the same name and same return type, but a different number of parameters or different parameter types.

Can I use arrow functions in methods?

Arrow function expressions are ill suited as methods, and they cannot be used as constructors. meaning that in our case, the enclosed scope would be the window object. Invoking the method clap() would simply attempt to increment the property claps on the window object.

Does TypeScript support arrow function?

ES6 version of TypeScript provides an arrow function which is the shorthand syntax for defining the anonymous function, i.e., for function expressions. It omits the function keyword. We can call it fat arrow (because -> is a thin arrow and => is a "fat" arrow).

Can a class overload properties in TypeScript?

Conclusion. Method overloading in Typescript differs from traditional programming languages like Java or C#. To overload methods, you can either choose optional parameters or function declarations.


1 Answers

You can write an inline type literal for the call signatures the function supports:

class TestOverloads2 {     private status = "blah";     public doStuff: {         (selector: JQuery): void;         (selector: string): void;     } = (selector: any) => {         alert(this.status);     } } 

That's sort of hideous, so you might want to extract it into an interface instead:

interface SelectByJQueryOrString {     (selector: JQuery): void;     (selector: string): void; }  class TestOverloads3 {     private status = "blah";     public doStuff: SelectByJQueryOrString = (selector: any) => {         alert(this.status);     } } 
like image 68
Ryan Cavanaugh Avatar answered Sep 21 '22 06:09

Ryan Cavanaugh