【发布时间】: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<T>(value: ?T): T { return ((value:any):T); },尽管我称之为unsafe_cast。
标签: node.js casting type-conversion flowtype