Skip to content

Commit

Permalink
Add some docs about %checks
Browse files Browse the repository at this point in the history
  • Loading branch information
apsavin committed Oct 17, 2017
1 parent 0efa130 commit a160946
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions website/en/docs/types/functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,54 @@ var num: number = method.call(42);
var str: string = method.call(42);
```

### Functions with %checks <a class="toc" id="toc-function-checks" href="#toc-function-checks"></a>

Sometimes you will want to move condition from `if` statement into a function

```js
function concat(a: ?string, b: ?string): string {
if (a && b) {
return a + b;
}
return '';
}
```
However, `flow` will see an error in the code below:
```js
function truthy(a, b): boolean {
return a && b;
}

function concat(a: ?string, b: ?string): string {
if (truthy(a, b)) {
// $ExpectError
return a + b;
}
return '';
}
```
You can fix it using `%checks` mark like this:
```js
function truthy(a, b): boolean %checks {
return !!a && !!b;
}

function concat(a: ?string, b: ?string): string {
if (truthy(a, b)) {
return a + b;
}
return '';
}
```
Such predicate functions must return immediately (i.e. you can not declare variables).
Also, it's not possible to call other predicate functions inside a predicate function.
### `Function` Type <a class="toc" id="toc-function-type" href="#toc-function-type"></a>
Sometimes it is useful to write types that accept arbitrary functions, for
Expand Down

0 comments on commit a160946

Please sign in to comment.