在 TypeScript 中,是否有一种安全的方式来编写 axiosResult.data.attendeeResults.username
In TypeScript, is there a safe way to write axiosResult.data.attendeeResults.username
除非出现严重错误,否则我希望我引用的 JavaScript 对象是这样的:
axiosResult.data.attendeeResults.username
里面会有真实的数据。即定义了data
,定义了attendeeResults
,定义了username
。如果其中任何一个未定义,我希望整个 express 只是安静地 return undefined 没有错误。
如何在 TypeScript 中执行此操作?或者甚至只是 EcmaScript 6?
一种解决方案是使用 non null assertion operator official doc
来自官方 TypeScript 发行说明:
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
建议将 ?
运算符添加到 javascript 以实现与 axiosResult?.data?.attendeeResults?.username
相同的用例,以便仅在 LHS 时读取 属性不是未定义或空的。它 returns undefined
否则
在文档中,[https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#non-null-assertion-operator] 在打字稿中,您可以使用 axiosResult!.data!.attendeeResults!.username
获得相同的结果。
除非出现严重错误,否则我希望我引用的 JavaScript 对象是这样的:
axiosResult.data.attendeeResults.username
里面会有真实的数据。即定义了data
,定义了attendeeResults
,定义了username
。如果其中任何一个未定义,我希望整个 express 只是安静地 return undefined 没有错误。
如何在 TypeScript 中执行此操作?或者甚至只是 EcmaScript 6?
一种解决方案是使用 non null assertion operator official doc
来自官方 TypeScript 发行说明:
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
建议将 ?
运算符添加到 javascript 以实现与 axiosResult?.data?.attendeeResults?.username
相同的用例,以便仅在 LHS 时读取 属性不是未定义或空的。它 returns undefined
否则
在文档中,[https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#non-null-assertion-operator] 在打字稿中,您可以使用 axiosResult!.data!.attendeeResults!.username
获得相同的结果。