[英]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.