Home > Blockchain >  accessing 'this' in exported function - typescript
accessing 'this' in exported function - typescript

Time:01-03

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 ?

CodePudding user response:

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

  • Related