简体   繁体   中英

'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)

userSchema.pre('save', async function(done) {
    if (this.isModified('pass')) {
        const hashed = await Password.toHash(this.get('pass'));
        this.set('pass', hashed);
    }
    done();
});

I am getting the following error from "this":

'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)

I heard the problem came from the arrow key, but I am not using an arrow key for the callback function? I am still getting an error. What gives?

I am also getting an error from "done":

Parameter 'done' implicitly has an 'any' type.ts(7006)

Could it be some kind of bug with Visual Studio Code?

It's not a bug in VS Code or in TypeScript. It is simply that there is not enough information from the call for TypeScript to determine what this will be bound to when the function is ultimately executed by Mongoose.

Assuming you have a type called User , you can fix this with an explicit this type annotation.

userSchema.pre('save', async function(this: User, done) {
    if (this.isModified('pass')) {
        const hashed = await Password.toHash(this.get('pass'));
        this.set('pass', hashed);
    }
    done();
});

Note that the syntax used to specify the type of this , is a special syntax in that it does not emit a parameter in the resulting JavaScript:

function(this: X) {}

compiles to

function() {}

Have you tried doing the following, i've had this same issue and I worked around like so...

// We generally explicitly provide a type to the arguments we are using...

userSchema.pre('save', async function(done: any) {
    const self: any = this;

    if (this.isModified('pass')) {
        const hashed = await Password.toHash(self.get('pass'));
        self.set('pass', hashed);
    }
    done();
});

From what I've come to understand, the error seeds from the typescript config which can be modified for implicit typings in order to not show the error.

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