Home > database >  Typescript "Object is possibly undefined" while assigning property
Typescript "Object is possibly undefined" while assigning property

Time:10-14

I have the following code:

cached.promise = mongoose
            .connect(MONGODB_URI as string, opts)
            .then(mongoose => {
                return mongoose;
            });

My editor underlines cached and gives an "Object is possibly undefined" error. Why is it doing this for an assignment? Shouldn't it not matter if cached.promise is undefined because the assignment operator is going to make it defined?

Edit: To settle the debate in the comments, I'd like to point out that the selected answer worked for me. The change I made to the code to get it working was this:

(cached as { promise: Promise<typeof mongoose> }).promise = mongoose
            .connect(MONGODB_URI as string, opts)
            .then(mongoose => {
                return mongoose;
            });

Edit 2: Wait, was that not a debate in the comments where everyone was saying the same thing, but rather just everyone correcting me? Now I feel like an idiot.

CodePudding user response:

The editor underlines cached because you are trying to assign a property to a variable that may not be defined at all. You need to ensure cached variable is defined and is an object as cached may be potentially undefined in your context:


if (typeof cached === 'object') {
  cached.promise = mongoose
    .connect(MONGODB_URI as string, opts)
    .then(mongoose => {
      return mongoose;
    });
}
  • Related