问题
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?
回答1:
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);
}
}
回答2:
It is a bit of a technicality, but you are no longer creating a function, you are creating a property (that happens to be a function).
You could solve your problem using naming rather than overloading though.
class TestOverloads2 {
private status = "blah";
public doStuffWithSelector = (selector: string) => {
alert(this.status);
}
public doStuffWithJqueryObject = (jqo: JQuery) => {
alert(this.status);
}
}
If there is significant duplication, you can put that in a common function that both named functions call, for example: this.sharedStuff()
.
来源:https://stackoverflow.com/questions/20646171/can-i-use-typescript-overloads-when-using-fat-arrow-syntax-for-class-methods