【问题标题】:How to abstract null/undefined checking with Flow?如何使用 Flow 抽象空/未定义检查?
【发布时间】:2017-11-14 22:18:10
【问题描述】:

sessionStorage.getItem() 被 Flow 视为 Maybe/Optional 类型。因此,为了使结果可用作非 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

【问题讨论】:

  • 我也不喜欢这种流动行为。在null 值的情况下,您真的需要unwrap 来引发错误吗?
  • 你不必扔。你可以在unwrap 中进行不安全的强制转换,即function unwrap&lt;T&gt;(value: ?T): T { return ((value:any):T); },尽管我称之为unsafe_cast

标签: node.js casting type-conversion flowtype


【解决方案1】:

您的返回类型正在将细化范围扩大到其原始类型。试试

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
}

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

'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`)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    • 2021-10-05
    相关资源
    最近更新 更多