在打字稿,有写axiosResult.data.attendeeResults.username一种安全的方式

问题描述 投票:0回答:2

除非不顺心的严重错误,我想到的是,JavaScript对象,我引用如下:

axiosResult.data.attendeeResults.username

将在它的真实数据。也就是说,data定义,attendeeResults定义和username定义。如果其中任何一个都没有定义,我想整个快递,只是静静地返回不确定的,没有错误。

我怎样才能在打字稿做到这一点?甚至只是EcmaScript的6?

typescript undefined
2个回答
1
投票

有一个建议给?经营者添加到JavaScript来实现相同的使用情况下,axiosResult?.data?.attendeeResults?.username因此,如果LHS不是未定义或为空的属性为只读。这否则返回undefined

在打字稿,从文档,[https://github.com/Microsoft/TypeScript/wiki/What's全新功能于打字稿#非空断言运营商]你可以使用axiosResult!.data!.attendeeResults!.username来得到相同的结果。


0
投票

一种解决方案是使用non null assertion operator official doc

从正式打字发行说明:

function processEntity(e?: Entity) {
    validateEntity(e);
    let s = e!.name;  // Assert that e is non-null and access name
}

你的情况,你可以对axiosResult.data检查:

axiosResult.data!.attendeeResults!.username
© www.soinside.com 2019 - 2024. All rights reserved.