Define function parameter types based on other parameters
- 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
Assessment
This issue has not been assessed yet.