[英]accessing 'this' in exported function - typescript
我試圖了解在導出的 function 中嘗試訪問/傳遞“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' 應該是 function scope 嗎? 還是全球object? 誰在隱藏這個變量,我該如何解決?
該錯誤來自noImplicitThis
編譯選項。 您可以刪除此選項(不推薦)或this
聲明類型,例如:
export async function main(this: unknown) {
try {
console.log(this);
} catch (e: any) {
}
}
游樂場鏈接: https://tsplay.dev/mLLpbm
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.