为何使用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
相关产品推荐
相关产品推荐

