Return TypeScript 中函数链的类型错误
Return type errors for function chaining in TypeScript
我是 TypeScript 的新手,目前正在将我的 JS 迁移到它。
我有一些实用程序函数,根据其输入可能 return 不同类型。
我创建了这个例子:
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() 的 return 值肯定是 MyElement,但编译器会抛出错误:
Property 'style' does not exist on type 'string | MyElement'.
Property 'style' does not exist on type 'string'. ts(2339)
如何在允许我链接方法的同时删除此错误?
我曾想过将方法分开,但这会导致很多功能。
多亏了评论,我才能够通过使用函数重载来解决它:
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');
我是 TypeScript 的新手,目前正在将我的 JS 迁移到它。 我有一些实用程序函数,根据其输入可能 return 不同类型。 我创建了这个例子:
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() 的 return 值肯定是 MyElement,但编译器会抛出错误:
Property 'style' does not exist on type 'string | MyElement'.
Property 'style' does not exist on type 'string'. ts(2339)
如何在允许我链接方法的同时删除此错误?
我曾想过将方法分开,但这会导致很多功能。
多亏了评论,我才能够通过使用函数重载来解决它:
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');