You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何使用array.at(-1)时TypeScript提示‘Object is possibly undefined’错误?

TypeScript中array.at(-1).key的「Object is possibly undefined」错误问题

在TypeScript中,使用array.at(-1).key访问数组最后一项的属性时,会触发「Object is possibly undefined」错误,而等价的array[array.length - 1].key写法却不会出现这个问题,甚至提前对array.at(-1)做非空判断后,错误依然存在。

无错误的索引访问写法

class P {
    public x: number
    public constructor(x: number) {
        this.x = x
    }
}

const a = [new P(1)]

console.log(a[a.length - 1].x)

这段代码通过a[a.length - 1]获取数组最后一项,访问其x属性不会触发TypeScript错误。

触发错误的at()写法

class P {
    public x: number
    public constructor(x: number) {
        this.x = x
    }
}

const a = [new P(1)]

console.log(a.at(-1).x)

将索引访问替换为a.at(-1)后,TypeScript会抛出「Object is possibly undefined」错误。

非空判断后仍触发错误

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)

即便提前通过a.at(-1) !== undefined做了非空校验,TypeScript依旧会抛出相同的错误提示。

内容的提问来源于stack exchange,提问作者Junee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 06:42:41