简体   繁体   中英

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:

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? or the global object? who is shadowing this variable and how can i work around that?

The error comes from noImplicitThis compilation option. You can either remove this option (not recommended) or declare the type for this such as:

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

    }
}

Playground link: https://tsplay.dev/mLLpbm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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