Leander Hass
Leander Hass

Reputation: 357

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.

Upvotes: 1

Views: 265

Answers (1)

Leander Hass
Leander Hass

Reputation: 357

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

Upvotes: 1

Related Questions