In my opinion, the most straightforward approach in this situation is to utilize Partial
:
type A = { b: string, c: number }
type Obj = Partial<A[]>
declare var apiData: Obj;
const check = apiData[0] // A | undefined
Alternatively, you have the option to employ a typeguard
type A = { b: string, c: number }
type Obj = A[]
declare var apiData: Obj;
const isEmpty = <Elem,>(arg: Elem[]): arg is never[] => arg.length === 0
if (isEmpty(apiData)) {
const x = apiData[0] // never
} else {
const x = apiData[0] // A
}
Moving on to the next type definition
type Obj = A[] | never[]
This solution may not function as expected due to the fact that never[]
extends A[]
type IsAssignable = never[] extends A[] ? true : false // true
Furthermore, you can enable the noUncheckedIndexedAccess
flag