我試圖理解我曾經嘗試在匯出的函式中訪問/傳遞“this”時遇到的以下錯誤,我有以下代碼:
export async function main() {
try {
console.log(this)
catch (e: any) {
}
嘗試編譯時給我這個錯誤:
src/main.ts:55:32 - error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.
55 console.log( this);
~~~~
src/main.ts:28:23
28 export async function main() {
~~~~
An outer value of 'this' is shadowed by this container.
我不明白為什么我在訪問它時遇到問題 - 'this' 應該是函式作用域嗎?還是全域物件?誰在隱藏這個變數,我該如何解決這個問題?
uj5u.com熱心網友回復:
錯誤來自noImplicitThis編譯選項。您可以洗掉此選項(不推薦)或宣告型別,this例如:
export async function main(this: unknown) {
try {
console.log(this);
} catch (e: any) {
}
}
游樂場鏈接:https : //tsplay.dev/mLLpbm
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/403096.html
標籤:
