【问题标题】:Undefined objects using Map().get() in Typescript在 Typescript 中使用 Map().get() 的未定义对象
【发布时间】: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


【解决方案1】:

尝试使用三元运算符使这变得困难,通过将变量分配给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>
})

【讨论】:

    猜你喜欢
    • 2020-08-11
    • 1970-01-01
    • 2022-11-30
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    相关资源
    最近更新 更多