Search code examples
node.jstypescripttslint

Object is possibly 'null'.ts(2531)


I am using Node with Typescript. I am finding a mongodb document and updating some values into it and then saving it. On the statement save it is showing this error. Below is the code:

let user = await User.findById(id);
if (user) {
  user = Object.assign(user, req.body);
  await user.save();  // on this line error is shown
} else {
  throw "User not found";
}

On the line await user.save() it is showing this error.


Solution

  • I'm not sure why, but mutating the user variable seems to be causing the issue.

    Rewriting it with a new variable works fine in the typescript playground for me (I had to cheat a bit to avoid having a real Mongoose model and I made up the types, but it should be the same idea):

    type User = {
        email: string;
        save: () => Promise<void>
    }
    
    declare let user: User | null;
    
    if (user) {
      const newUser = Object.assign(user, { email: "test@example.com"})
      newUser.save();  // on this line error is shown
    } else {
      throw "User not found";
    }
    

    https://www.typescriptlang.org/play?ssl=1&ssc=1&pln=13&pc=2#code/C4TwDgpgBAqgzhATlAvFA3gKCjqEC2AhgJYA2AXFHMIsQHYDmA3NrnIQG4SUAUAlKgB8UAAqIA9vmIIAPB3HEAJoMwBfTJkUQAxqUKJopCMCgBXBIkrwkUAD5Q6p0qRaZiAMyg9zSAVhza4nTUDhAA7tbIaADyAEYAVjrAAHSEcHDEDHTeFgA0GHhEZJQARMAQ1AACEAAehPhgRsmB+CWqfKx04ZHJ7Fz8TDgA9ENQQVDAABbSUKT00EgSyDNwk+JhdGp4pAgYrFMSYVAlkQ7iJu7ipnSKJSyqQA