JavaScript
flow
null安全

flowtype の Maybe と Optional を理解する


オブジェクトのプロパティでの例

まずはどちらも使わない例

type Book = {

name: string,
}

type Standard = {
book: Book,
}

const a0: Standard = { book: { name: 'js' } }
const b0: Standard = { book: null } // Error !!
const c0: Standard = { book: undefined } // Error !!
const d0: Standard = {} // Error !!

console.log(a0.book.name) // ok


Optional property

type Optional = {

book?: Book,
}

const a1: Optional = { book: { name: 'js' } }
const b1: Optional = { book: null } // Error !!
const c1: Optional = { book: undefined }
const d1: Optional = {}

console.log(a1.book.name) // Error !!

if (a1.book) {
console.log(a1.book.name)
}

null は許容しません


Maybe property

type Maybe = {

book: ?Book,
}
const a2: Maybe = { book: { name: 'js' } }
const b2: Maybe = { book: null }
const c2: Maybe = { book: undefined }
const d2: Maybe = {} // Error !!

console.log(a2.book.name) // Error !!

if (a2.book) {
console.log(a2.book.name)
}

空を許容しますがプロパティは必要です。


Maybe and Optional property

type MaybeOptional = {

book?: ?Book,
}
const a3: MaybeOptional = { value: { name: 'js' } }
const b3: MaybeOptional = { value: null }
const c3: MaybeOptional = { value: undefined }
const d3: MaybeOptional = {}

console.log(a3.book.name) // Error !!
a3.book

if (a3.book) {
console.log(a3.book.name)
}

紛らわしいので使わないかもしれません。


関数の引数での例

まずはどちらも使わない例

function assertStandard(book: Book) {

book.name // ok
}

assertStandard({ name: 'js' })
assertStandard(null) // Error !!
assertStandard(undefined) // Error !!
assertStandard({}) // Error !!
assertStandard() // Error !!


Optional Argument

function assertOptional(book?: Book) {

book.name // Error!
if (book) {
book.name
}
}

assertOptional({ name: 'js' })
assertOptional(null) // Error!!
assertOptional(undefined)
assertOptional()

nullを許容しません。


Maybe Argument

function assertMaybe(book: ?Book) {

book.name // Error !!
if (book) {
book.name
}
}

assertMaybe({ name: 'js' })
assertMaybe(null)
assertMaybe(undefined)
assertMaybe()

引数がないけど許されます。


Optional and Maybe Argument

function assertMaybeOptional(book?: ?Book) {

book.name // Error !!
if (book) {
book.name
}
}

assertMaybeOptional({ name: 'js' })
assertMaybeOptional(null)
assertMaybeOptional(undefined)
assertMaybeOptional()


参考