本文介绍了在类方法中使用粗箭头语法时,可以使用TypeScript重载吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经从常规形式转换了一些类:
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?
推荐答案
您可以为函数支持的调用签名编写内联类型文字:
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);
}
}
这篇关于在类方法中使用粗箭头语法时,可以使用TypeScript重载吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!