简体   繁体   中英

Return type errors for function chaining in TypeScript

I'm new to TypeScript and currently migrating my JS to it. I have some utility functions that may return different types based on its input. I have created this example:

class MyElement {
    element: HTMLElement;

    constructor(element: HTMLElement) {
        this.element = element;
    }
    html(html: string | true = true): string | MyElement {
        if (html === true) {
            return this.element.innerHTML;
        } else {
            this.element.innerHTML = html;
            return this;
        }
    }
    style(prop: string, value: string) {
        this.element.style.setProperty(prop, value);
        return this;
    }
}

var el = new MyElement(document.getElementById('myID'));
el.html('Lorem Ipsum').style('color', 'red');

Although the return value of el.html() will definitely be MyElement the Compiler throws the error:

Property 'style' does not exist on type 'string | MyElement'.
  Property 'style' does not exist on type 'string'. ts(2339)

How can i remove this error while still allowing me to chain the methods?

I have thought of seperating the methods but that would result in a lot of functions.

Thanks to the comments I was able to solve it by using function overloading:

class MyElement {
    element: HTMLElement;

    constructor(element: HTMLElement) {
        this.element = element;
    }

    html(html: string): MyElement;
    html(html: true): string;

    html(html: string | true = true): string | MyElement {
        if (html === true) {
            return this.element.innerHTML;
        } else {
            this.element.innerHTML = html;
            return this;
        }
    }
    style(prop: string, value: string) {
        this.element.style.setProperty(prop, value);
        return this;
    }
}

var el = new MyElement(document.getElementById('myID'));
el.html('Lorem Ipsum').style('color', 'red');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM