【发布时间】:2019-05-25 17:12:13
【问题描述】:
所以我有一些 userObject 有属性
public userId: string
public displayName: string
public username: string
还有一个有属性的productObject
public productId: string
public userIds: string[] | null
我正在这样做:
private _$customerUsers: Map<string, UserObject> | undefined = undefined
private _onUsers = (bundle: DataBundleObject<UserObject>) => {
this._$customerUsers = new Map()
for (let customerUser of bundle.listOfData) {
this._$customerUsers.set(customerUser.userId, customerUser)
}
}
我想做类似的事情
productObject.userIds.map(user => {<span>this._$customerUsers.get(user).username</span>})
因为 VScode 告诉我Object is possibly 'undefined' 我无法运行,所以我尝试了三元运算符:
this._$customerUsers ? this._$customerUsers.get(user) ? this._$customerUsers.get(user).username
但它仍然说最后一个可能是undefined。这怎么可能?第二个三元表达式应检查返回对象是否为undefined。
更新
奇怪的是我能做到
productObject.userIds.map(user => {
if (this._$customerUsers) {
var userO = this._$customerUsers.get(user)
if (userO === undefined) {<Tag color='red'>N/A</Tag>}
else {
<Tag color="blue" key={user}>{userO.username}</Tag>
}
}
<Tag color='red'>N/A</Tag>
})
但不是
productObject.userIds.map(user => {
if (this._$customerUsers) {
if (this._$customerUsers.get(user) === undefined) {<Tag color='red'>N/A</Tag>}
else {
<Tag color="blue" key={user}>{this._$customerUsers.get(user).username}</Tag>
}
}
<Tag color='red'>N/A</Tag>
})
关于它是一个变量的一些东西使它更好地评估。
【问题讨论】:
-
TypeScript 编译器不知道
.get()每次都返回相同的结果。 -
有什么理由需要地图吗?为什么不是 POJO?
-
它是否说
_$customerUsers可能未定义?因为这正是你的_$customerUsers声明所说的。 -
@FranklinHarvey:是的,但恐怕
.get(user)可能第一次返回值,而undefined第二次返回。 -
是的;这是因为编译器知道
userO在调用之间不会改变,而它不知道this._$customerUsers.get(user)在调用之间不会改变。
标签: javascript reactjs typescript ternary-operator