gpt4 book ai didi

typescript 未定义强制

转载 作者:搜寻专家 更新时间:2023-10-30 21:38:46 24 4
gpt4 key购买 nike

当我发现这段代码时,我正在写一个 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 possibly 'undefined':

enter image description here

如果已经检查过它不是 state.myself undefined 怎么可能?

最佳答案

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

关于 typescript 未定义强制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45895905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com