简体   繁体   English

function 链接在 TypeScript 中的返回类型错误

[英]Return type errors for function chaining in TypeScript

I'm new to TypeScript and currently migrating my JS to it.我是 TypeScript 的新手,目前正在将我的 JS 迁移到它。 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:尽管 el.html() 的返回值肯定是 MyElement,但编译器会抛出错误:

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:感谢评论,我能够通过使用 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