![](/img/trans.png)
[英]Using Map.get() method in typescript, returns undefined, while I am handling undefined
[英]Undefined objects using Map().get() in Typescript
所以我有一些具有屬性的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>
})
關於它是變量的一些事情使它更好地進行評估。
嘗試使用三元運算符使此操作變得困難,它通過向this._$customerUser.get()
的返回值分配變量來更好地工作:
productObject.userIds.map(user => {
if (this._$customerUsers) {
var singleUser = this._$customerUsers.get(user)
if (singleUser === undefined) {<span>N/A</span>}
else {
return <span key={user}>{singleUser.username}</span>
}
}
return <span>N/A</span>
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.