首页 > 解决方案 > Flow js谓词函数

问题描述

我正在尝试使用谓词函数(https://flow.org/en/docs/types/functions/#toc-predicate-functions),但它不起作用。

给定以下代码:

/* @flow */
// Some function we need exact types for
const someFunc = (addressLine1: string, city: string, zip: string) => ({})

// Predicate
function checker(addressLine1: ?string, city: ?string, zip: ?string): boolean %checks {
  return Boolean(addressLine1 && city && zip)
}

// Logic
const addressLine1: ?string = 'a'
const city: ?string = 'b'
const zip: ?string = 'c'

if(checker(addressLine1, city, zip)){
  someFunc(addressLine1, city, zip)
}

阅读文档后,我希望上面的代码没有任何错误,但是 Flow 抱怨addressLine1,cityzip在调用someFunc().

Here's a working (well, erroring) example: https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoYwwGU4FsCmYUArgHYDGALgJZylgKGn74AmY+AHgIZViUBPAA74AzkTgAnVOTqjKYUXnwAxMuTABeMAApurVpLGiAMtWYBGAFyLKk8wHMANGHLVBN+fdLOwAL2ohTztHAEotAD5dAG8AX1DUdEwABSNWanJuSnxUEgoaOlcAC3xyAGt8ST0DI1FTc3xrMAB+L0cXNw8Wtp8XAKDukJ9QmwAjODgYfG56AFJyEvLxaNQwMCNKYkl6ACEJqZnqw2MzSzAAMnPXdwELq-6E2MSMMBM4BwyZOQV9Y7rTxo2VpDBxaMAAcm44K+pHk1y6wO8oO04NG0NksIU-SBPWREPI0NQ1CgOgWpQqVV+tXqlg6Nz6gVCoRWayUBDUFCO1IBFjpggZQkeQA

任何洞察我做错了什么?

在此先感谢,丹

标签: javascriptflowtypepredicate

解决方案


我相信这种情况下的问题是将返回值包装在Boolean(). 一旦我删除错误就解决了。

更正的代码:

/* @flow */
// Some function we need exact types for
const someFunc = (addressLine1: string, city: string, zip: string) => ({})

// Predicate
function checker(addressLine1: ?string, city: ?string, zip: ?string): boolean %checks {
  return !!addressLine1 && !!city && !!zip
}

// Logic
const addressLine1: ?string = 'a'
const city: ?string = 'b'
const zip: ?string = 'c'

if(checker(addressLine1, city, zip)){
  someFunc(addressLine1, city, zip)
}

In "Try Flow": https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoYwwGU4FsCmYUArgHYDGALgJZylgKGn74AmY+AHgIZViUBPAA74AzkTgAnVOTqjKYUXnwAxMuTABeMAApurVpLGiAMtWYBGAFyLKk8wHMANGHLVBN+fdLOwAL2ohTztHAEotAD5dAG8AX1DUdEwABSNWanJuSnxUEgoaOlcAC3xyAGt8ST0DI1FTc3xrMAB+L0cXNw8Wtp8XAKDukJ9QmwAjODgYfG56AFJyEvLxaNQwMCNKYkl6AEId-UNjM0swADJTsD3OgTOLvf7UWMSMMBM4BwyZOQUD2vrLGytIYOLRgADk3DBX1I8lc7gEgJ6IO0YNGUNkMIU-URwNBYPIUNQ1CgOgWpQqVV+RwaFg68L6gVCoRWayUBDUFGqhzqx0adMEDKECViQA


推荐阅读