gpt4 book ai didi

node.js - 如何使用 Flow 抽象空/未定义检查?

转载 作者:太空宇宙 更新时间:2023-11-03 23:02:20 36 4
gpt4 key购买 nike

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

现在我想抽象空/未定义检查,但 Flow 并没有停止提示可能的空和未定义类型:

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

最佳答案

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

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

关于node.js - 如何使用 Flow 抽象空/未定义检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44516369/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com