假設我有一個如下所示的物件:
const console = {
write(text: string) {
/* logic */
return this;
},
writeLine(text: string) {
/* logic */
return this;
}
};
這里的write和writeLine方法的回傳型別應該是什么?
我知道我們可以定義一個介面并將其設定為回傳型別,但是有沒有其他方法可以設定參考該物件的型別?
uj5u.com熱心網友回復:
您可以通過這種方式顯式定義回傳型別:
const _console = {
write(text: string): typeof this {
/* logic */
return this;
},
writeLine(text: string): typeof this {
/* logic */
return this;
}
};
操場
或者您可以將您的定義console為一個類并使用this:
class Console {
write(text: string): this {
/* logic */
return this;
}
writeLine(text: string): this {
/* logic */
return this;
}
};
操場
我希望它能讓 ESLint 開心 :D
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/332677.html
標籤:打字稿
