簡體   English   中英

function 鏈接在 TypeScript 中的返回類型錯誤

[英]Return type errors for function chaining in TypeScript

我是 TypeScript 的新手,目前正在將我的 JS 遷移到它。 我有一些實用函數可能會根據其輸入返回不同的類型。 我創建了這個例子:

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

盡管 el.html() 的返回值肯定是 MyElement,但編譯器會拋出錯誤:

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

如何在仍然允許我鏈接方法的同時刪除此錯誤?

我曾考慮過將方法分開,但這會產生很多功能。

感謝評論,我能夠通過使用 function 重載來解決它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM