An issue arises in Typescript with the error message "Object is possibly 'undefined'" when attempting to access an element at a negative index using
array.at(-1).key //array[array.length - 1].key
. This error does not occur in the following code:
class P {
public x: number
public constructor(x: number) {
this.x = x
}
}
const a = [new P(1)]
console.log(a[a.length - 1].x)
However, the error is triggered when using the code snippet below:
class P {
public x: number
public constructor(x: number) {
this.x = x
}
}
const a = [new P(1)]
console.log(a.at(-1).x)
The error also occurs when checking if the value is undefined in the example provided:
class P {
public x: number
public constructor(x: number) {
this.x = x
}
}
const a = [new P(1)]
if (a.at(-1) !== undefined) console.log(a.at(-1).x)