简体   繁体   English

使用前分配的变量 typescript

[英]Variable assigned before being used typescript

Im using typescript for my next nodejs app, and I ran into the following problem.我将 typescript 用于我的下一个 nodejs 应用程序,我遇到了以下问题。 Here is my code:这是我的代码:


class AuthService {
    public async init(req: Request, res: Response) {
        let user: IUser | null;
        const userId = res.locals.userId;
        if (userId) {
            user = await User.findById(userId);
        }

        return res.send({user}); // error here, as in the title
    }
}

I get the ts error: Variable 'user' is used before being assigned.我收到 ts 错误:在分配之前使用了变量“用户”。 What do i do wrong?我做错了什么?

I guess the problem is that the value is only assigned to a variable when the if condition is met.我想问题是只有在满足 if 条件时才将值分配给变量。 So one of the solutions would be to assign it some value during declaration.因此,解决方案之一是在声明期间为其分配一些值。 Like let user: IUser |喜欢让用户:IUser | null = null; null = null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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