【问题标题】:TypeScript undefined coercingTypeScript 未定义的强制
【发布时间】:2018-02-04 08:38:43
【问题描述】:

当我发现这段代码时,我正在编写一个 Redux reducer:

export function users(state: { myself: IUser | undefined, users: IUser[] } = { myself: undefined, users: [] }, action: UserActions) {
  const mself = state.myself;
  if (action.type === EMyselfAction.CHANGE_MYSELF_CONFIG && state.myself !== undefined) {
    return {
      myself: myself(mself, action),
      users: state.users.map((u) => user(u, action, state.myself.id)),
    };
  }
  ...
}

正在输出错误 Object is possible 'undefined':

state.myself如果已经检查过,怎么可能是未定义的?

【问题讨论】:

  • 您能否将错误消息作为文本发布,而不是仅将其发布为屏幕截图?这可能会帮助其他面临相同错误的人通过 google 查找问题。
  • TS 不会因为断言(T is 类型保护或!== null 检查)而总是“更改”参数的类型。您可能会更幸运地将 state.myself 替换为 mself 并反对(更容易更改局部变量)。
  • @k0pernikus 我知道如何抑制该错误。问题是只有在 state.myself 不是未定义的情况下才会强制执行 if 正文。
  • @ssube 这是一种解决方案,但是为什么编译器不断言类型?很明显,IMO state.myself 不是由于断言而未定义的。

标签: typescript undefined type-coercion


【解决方案1】:

我认为这是因为 state.myself 处于不同的范围内。

export function users(state: { myself: IUser | undefined, users: IUser[] } = { myself: undefined, users: [] }, action: UserActions) {
  const mself = state.myself;
  if (action.type === EMyselfAction.CHANGE_MYSELF_CONFIG && state.myself !== undefined) {
    state.myself // (property) myself: IUser

    const foo = () => {
       state.myself // but here is (property) myself: IUser | undefined
    }
    // ...
  }
  ...
}

我认为您不能保证,因为您可以在其他地方使用它(不仅在state.myself !== undefined 的那个分支中)。所以你可以这样做:

export function users(state: { myself: IUser | undefined, users: IUser[] } = { myself: undefined, users: [] }, action: UserActions) {
  const mself = state.myself;
  if (action.type === EMyselfAction.CHANGE_MYSELF_CONFIG && state.myself !== undefined) {
    const id = state.myself.id;
    return {
      myself: myself(mself, action),
      users: state.users.map((u) => user(u, action, id)),
    };
  }
  ...
}

【讨论】:

    猜你喜欢
    • 2017-01-14
    • 2018-12-27
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 2017-12-29
    • 2016-12-14
    相关资源
    最近更新 更多