Reputation: 1931
I'm having trouble performing operations on an array item using .split() because FLOW thinks it COULD be undefined.
export const getTokenFromCookieRes = (cookies: string[]): mixed => {
if (!cookies) {
return undefined
}
if (0 in cookies) {
return cookies[0] // cookies[0] returns an error for possibly being undefined
.split(';')
.find(c => c.trim().startsWith('jwt='))
.split('=')[1]
} else {
return undefined
}
}
Upvotes: 0
Views: 349
Reputation: 1492
The issue is not that cookies[0]
might be undefined
; it's that the result of find()
could be undefined
. You need to check the results of find()
before trying to call split()
on the string.
const getTokenFromCookieRes = (cookies?: string[]): mixed => {
if (!cookies) {
return undefined
}
if (!!cookies[0]) {
const jwt = cookies[0] // No issues here
.split(';')
.find(c => c.trim().startsWith('jwt='))
return jwt && jwt.split('=')[1];
}
}
Upvotes: 3