2017-08-26 107 views
2

我正在寫一個終極版減速時,我發現這個代碼:打字稿未定義強迫

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)), 
    }; 
    } 
    ... 
} 

是輸出錯誤對象可能是「未定義」:

enter image description here

怎麼能state.myself未定義,如果它已被檢查,它不是?

+0

的可能的複製【如何抑制打字稿?「錯誤TS2533:對象可能是‘空’或‘未定義’」](https://stackoverflow.com/questions/40349987/如何禁止打字腳本錯誤ts2533對象是可能null或undefine) – k0pernikus

+0

您能否請將錯誤消息作爲文本發佈,而不是隻發佈它作爲截圖?這可能會幫助其他人面臨同樣的錯誤通過谷歌找到問題。 – k0pernikus

+0

由於斷言('T is' type guard或'!== null'檢查),TS不會總是「改變」參數的類型。你可能有更好的運氣用'mself'替換'state.myself'並聲明反對(局部變量更容易改變)。 – ssube

回答

2

我認爲這是因爲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)), 
    }; 
    } 
    ... 
}