Szczepan Hołyszewski
Szczepan Hołyszewski

Reputation: 3167

Why doesn't TypeScript insist that someArray[0] can be undefined?

I have these two getters in my class:

    get jobs(): Job[]
    {
        return Object.values(this.#jobs);
    }

    get job(): Job
    {
        return this.jobs[0];
    }

Why doesn't TypeScript 4.2.3 complain that this.jobs[0] can be undefined? It allows me to return it as Job from the second getter, but the array returned by get jobs() is in no way guaranteed to be non-empty.

Upvotes: 1

Views: 91

Answers (1)

thedude
thedude

Reputation: 9812

the noUncheckedIndexedAccess config value will add undefined to the type returned by an index access.

Upvotes: 3

Related Questions