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

前端 未结 2 2039
眼角桃花
眼角桃花 2020-12-16 09:56

I\'ve converted some classes from the conventional form:

class TestOverloads {
    private status = \"blah\";
    public doStuff(selector: JQuery);
    publi         


        
相关标签:
2条回答
  • 2020-12-16 10:31

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-16 10:56

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

    0 讨论(0)
提交回复
热议问题