typescriptmongoosemongoose-schematypescript-genericstypescript-utility

Typescript Partial<T> causing undefined error even with `?` chaining or conditional Checks


I have a mongoose document stored as follows:

const currentGuildAlerts: Partial<mongoose.Document<IServerSchema> | null> = await Server.findOne(query).exec();

With the use of Partial<T> (as i only getting a single path from the IServerSchema returned from the query), I understand that Partial chains a ? to the end of each property in the interface. But i should be able to get around it by using a conditional check for the value right?

if(currentGuildAlerts) currentGuildAlerts.get("symbol_alerts").btc_alerts;

This still gives me the error : Cannot invoke an object which is possibly 'undefined'.

I even tried to do

currentGuildAlerts?.get("symbol_alerts").btc_alerts;

Still doesn't seem to solve the problem. What am i doing wrong here?


Solution

  • Partial means that the properties of an object might be undefined. You are making sure that the currentGuildAlerts object isn't null but you haven't checked that the property exists.

    You need an optional chaining ?. after get as well since you have said that all properties of the Document might be undefined.

    const currentGuildAlerts: Partial<mongoose.Document<IServerSchema>> | null = await Server.findOne(query).exec();
    
    const alerts = currentGuildAlerts?.get?.("symbol_alerts").btc_alerts;
    

    Perhaps is makes more sense to move the Partial inside the Document?

    const currentGuildAlerts: mongoose.Document<Partial<IServerSchema>> | null = await Server.findOne(query).exec();
    
    const alerts = currentGuildAlerts?.get("symbol_alerts").btc_alerts;