【问题标题】:Node + TypeScript: 'this' implicitly has type 'any'Node + TypeScript:“this”隐含类型“any”
【发布时间】:2020-12-17 19:43:16
【问题描述】:

我遇到了无法解决的 TypeScript 问题:

我正在使用 mongoose 架构的 post 函数在用户注册后立即为他/她生成一个配置文件(配置文件模型)(通过用户模型)。

我收到与 this 相关的类型 error。即使代码工作正常。所以我正在使用 ** // @ts-ignore **

接口:

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;
}

更多代码:

// 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 }

非常感谢您的帮助,这让我发疯了。

【问题讨论】:

    标签: node.js typescript express mongoose typescript-typings


    【解决方案1】:

    Schemapost() 方法回调函数的类型中没有指定this 的类型。无论如何它都可以工作,因为 this 的值在 javascript 中可能是一件复杂的事情,但它并没有声明以这种方式工作。

    如果你想要新创建的文档,那么 that actually gets passed in as an argument 到回调。

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

    Playground

    【讨论】:

    • 非常感谢。工作并理解。
    猜你喜欢
    • 2021-12-11
    • 2019-08-04
    • 1970-01-01
    • 2017-06-16
    • 2020-09-25
    • 2019-06-08
    • 2021-09-27
    • 2020-07-30
    • 2018-08-23
    相关资源
    最近更新 更多