打字稿未定义强制

TypeScript undefined coercing

我在写一个 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 可能是 'undefined':

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

我认为那是因为 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)),
    };
  }
  ...
}