I had this error in strict typescript with the code:

    let adam = await db.contacts.orderBy('lastName').last();
    console.log(`Found contact: ${adam.firstName} ${ada?.lastName} (id: ${adam.id})`);

Producing the error:

Error: src/app/core/services/database/database.service.ts:65:35 - error TS2532: Object is possibly 'undefined'.

Solution

The solution is to add question marks after the adam variable. This is called optional chaining. At its core, optional chaining lets us write code where TypeScript can immediately stop running some expressions if we run into a null or undefined

    let adam = await db.contacts.orderBy('lastName').last();
    console.log(`Found contact: ${adam?.firstName} ${adam?.lastName} (id: ${adam?.id})`);

 

 

Tags