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