How to solve TS2532 Object is possibly 'undefined'. with an Array?

Viewed 436

I have:

interface CompanyInfoProps {
    data: Company;
}

Where:

declare interface Company {
    /// some stuff
    id: string;
    companyAdmins?: CompanyAdmin[];
}

I am trying to do:

{data.companyAdmins[0].user.firstName}

But I get the error:

Object is possibly 'undefined'.  TS2532

I tried {data.companyAdmins?.length > 0 && data!.companyAdmins[0]!.user?.firstName} but I get the same error. What am I doing wrong?

4 Answers

Do this:

{data.companyAdmins?.[0]?.user?.firstName}

Use Optional Chaining

You need to use optional chaining to comply with the TypeScript error.

// just suffix `?` character at the
// end of a nullable or optional field

data.companyAdmins?.[0]?.user.firstName
// ---------------^----^---------------

Additional optional chaining would be required if user can be nullable or undefined as well and so on.

data.companyAdmins?.[0]?.user?.firstName
// ---------------^----^-----^----------

You should ashure typescript that companyAdmins is defined
Try

if (data?.companyAdmins) {
    // your code
}

The question is which part of the chain is undefined? We can't know if data might be undefined since we don't know how that's declared but let's assume it's the data part in CompanyInfoProps and therefore it is not undefined.

companyAdmins might be undefined because it's declared optional.

companyAdmins![0] might be undefined because the array might be empty but TS will only warn against that if the option noUncheckedIndexedAccess is set in TSConfig.

We don't know how CompanyAdmin looks like but again let's assume that it always has a user set and that user always has a firstName set.

So overall in your case the one-liner would be:

data.companyAdmins?.[0].user.firstName

If you're using noUncheckedIndexedAccess then it would be:

data.companyAdmins?.[0]?.user.firstName

However you might want to add some checks:

{data.companyAdmins && data.companyAdmins.length > 0 ? data.companyAdmins[0]!.user.firstName : undefined}
Related