Karan Kumar
Karan Kumar

Reputation: 3176

Node + TypeScript: 'this' implicitly has type 'any'

I have an issue with TypeScript which I am not able to resolve:

I am using a mongoose schema's post function to generate a profile(Profile model) for a user as soon as he/she signs up (via User model).

I am getting a type error related to this. Even though the code works fine. So i am using ** // @ts-ignore **

Interfaces:

interface UserAttrs {
    firstName: string;
    lastName: string;
    email: string;
    password: string;
}

interface UserDoc extends mongoose.Document {
    firstName: string;
    lastName: string;
    email: string;
    password: string;
}
// adding custom build function
interface UserModel extends mongoose.Model<UserDoc> {
    build(attrs: UserAttrs): UserDoc;
}

Further code:

// schema 
const userSchema = new mongoose.Schema({
    firstName: { type: String, required: true },
    lastName: { type: String, required: true },
    email: { type: String, required: true },
    password: { type: String, required: true }
}, { // schema options 
    toJSON: {
        transform(doc, ret) {
            ret.id = ret._id;
            delete ret._id;
            delete ret.password;
            delete ret.__v;
        }
    }
});

// generate profile for user  
userSchema.post('save', async function () {
    // @ts-ignore                              <---- TS ERROR
    let firstName = this.get('firstName');
    // @ts-ignore                              <---- TS ERROR
    let lastName = this.get('lastName');
    // @ts-ignore                              <---- TS ERROR
    let user = this.get('id');
    // @ts-ignore
    const profile = new Profile({
        firstName, lastName, user
    })
    await profile.save();
})
// configuring custom build function 
userSchema.statics.build = (attrs: UserAttrs) => {
    // builds a new user for us
    return new User(attrs);
}

const User = mongoose.model<UserDoc, UserModel>('User', userSchema)
export { User }

I would really appreciate the help, this is making me crazy.

Upvotes: 1

Views: 443

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187004

The type of this is not specified in the typings for the Schema's post() method callback function. It may work anyway because the value of this can be a complicated thing in javascript, but it's not declared to work that way.

If you want the newly created document, then that actually gets passed in as an argument to the callback.

userSchema.post('save', async (newUser) => {
    let firstName = newUser.get('firstName');
    let lastName = newUser.get('lastName');
    let user = newUser.get('id');
    //...
}

Playground

Upvotes: 1

Related Questions