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

怎甘沉沦 提交于 2019-11-30 17:06:49

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);
    }
}

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().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!