const getAccessToken = () => { if (localStorage.getItem('tokens')) { const token = JSON.parse(localStorage.getItem('tokens'))['accessToken']; return token } else { return null; } }
错误:
Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'.
我尝试声明type:any,但问题仍然没有解决
尝试移动表达式 localStorage.getItem('tokens')
localStorage.getItem('tokens')
const getAccessToken = () => { let tokens = localStorage.getItem('tokens') if (tokens) { const token = JSON.parse(tokens)['accessToken']; return token } else { return null; } }
Playground
这里的问题是,当您使用表达式时,编译器无法将其与 if string . 相反,它仍然被考虑 string | null .
if
string
string | null
你只需要 !
!
const getAccessToken = () => { if (localStorage.getItem('tokens')) { const token = JSON.parse(localStorage.getItem('tokens')!)['accessToken']; return token } else { return null; } }
有时编译器需要 告诉 提醒 怎么办