简体   繁体   English

在导出的 function - typescript 中访问“this”

[英]accessing 'this' in exported function - typescript

I am trying to understand the following error that i am getting once trying to access/pass 'this' in an exported function, I have the following code:我试图了解在导出的 function 中尝试访问/传递“this”时遇到的以下错误,我有以下代码:

export async function main() {
try {
    console.log(this)
catch (e: any) {

}

which give me this error when trying to compile:这在尝试编译时给了我这个错误:

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.

I don't understand why i have problem accessing it - should 'this' be the function scope?我不明白为什么我无法访问它 - 'this' 应该是 function scope 吗? or the global object?还是全球object? who is shadowing this variable and how can i work around that?谁在隐藏这个变量,我该如何解决?

The error comes from noImplicitThis compilation option.该错误来自noImplicitThis编译选项。 You can either remove this option (not recommended) or declare the type for this such as:您可以删除此选项(不推荐)或this声明类型,例如:

export async function main(this: unknown) {
    try {
        console.log(this);
    } catch (e: any) {

    }
}

Playground link: https://tsplay.dev/mLLpbm游乐场链接: https://tsplay.dev/mLLpbm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM