如何用Flow抽象null / undefined检查?

时间:2017-06-13 08:40:50

标签: node.js casting type-conversion flowtype

Flow将

sessionStorage.getItem()视为Maybe / Optional类型。因此,必须满足以下条件才能使结果可用作非可选类型或Maybe类型的字符串类型:

const accessToken1 = sessionStorage.getItem('accessToken')
if (!accessToken1) throw new Error('Unwrapping not possible because the variable is null or undefined!')
'Hello ' + accessToken1 // no complaints by Flow

现在我想抽象null / undefined检查,但Flow不会停止抱怨可能的null和undefined类型:

function unwrap<T>(value: T): T {
  if (!value) throw new Error('Unwrapping not possible because the variable is null or undefined!')
  return value // at this point Flow should understand it cannot be of type Optional or Maybe
}

'Hello ' + unwrap('World!')     // works
'Hello ' + unwrap(null)         // complains as expected with "null This type cannot be added to string"
'Hello ' + unwrap(undefined)    // complains as expected with "null This type cannot be added to string"
const nullString = 'null'
'Hello ' + unwrap(nullString)   // works
const accessToken2 = sessionStorage.getItem('accessToken')
'Hello ' + unwrap(accessToken2) // null/undefined This type cannot be added to string
const accessToken3 = (sessionStorage.getItem('accessToken'): string) // null/undefined This type cannot be added to string
'Hello ' + unwrap(accessToken3) // no complaints by Flow

1 个答案:

答案 0 :(得分:3)

您的返回类型正在将细化扩展回原始类型。尝试

function unwrap<T>(value: ?T): T { // Note the `?T`
    if (!value) throw new Error('Unwrapping not possible because the variable is null or undefined!')
    return value // at this point Flow should understand it cannot be of type Optional or Maybe
}

您的一些评论似乎被误导了。以下是我看到的必要更正:

'Hello ' + unwrap(null) // Not an error (I've opted for runtime errors with my `throw`)
'Hello ' + unwrap(undefined) // Not an error (I've opted for runtime errors with my `throw`)