0
sessionStorage.getItem()
は、フロー別のオプション/タイプとして処理されます。Flowでnull/undefinedのチェックを抽象化する方法は?
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
を今、私は抽象ヌル/未定義のチェックをしたいのですが、流れが不満停止しない:だから次はたぶん入力オプションタイプのかではなく、文字列型として結果を使用可能にする必要があります可能なヌルと未定義の型:
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'が必要ですか? – adrice727
あなたは投げる必要はありません。あなたは 'unwrap'の中で安全でないキャストを行うことができます。つまり' function unwrap(value:?T):T {return((value:any):T); } 'と呼びますが、私は' unsafe_cast'と呼んでいます。 –
popham