facebook / facebook/flow

Define function parameter types based on other parameters

Open
#3,638 3 comments 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
22.3k
Forks
1.9k
PR merge metrics
No merged PRs in 30d

Description

Say I have a function, `buildModel` which will return an object literal with a function `create` that may or may not be overridden by an `options` object:

```typescript
type Options = {
create?: () => {
// Code that doesn't use operation()
}
...
}

type Model = {
create: () => void,
...
}

const buildModel = (
options : Options,
operation : SomeFunctionWithReturnValue,
) : Model => {
create: () => {
...
const result = operation();
// Do stuff with result
...
},

...options,
}

// This causes flow error due to `operation` being null
const modelA = buildModel({ create: () => { // Code that doesn't use operation } });
```

In the case that **create** is not overridden, **operation** is called and the result of this function is used. However, we might want to call **buildModel** with a custom **create** function that doesn't take the **operation** function, in which case **operation** is null. In this case, we get a flow error because the **create** function defined in **buildModel** uses the result of **operation**.

So my question is, can we make **operation** a _maybe_ parameter based on whether or not **options** contains the **create** function? Of course we could make it a _maybe_ and then do checks to see if operation exists within the **create** function, but it would be nice to avoid that if we could do the check through types alone.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.