facebook / facebook/flow

Typing result of function which is influenced by optional parameter

Open
#5,234 0 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

Example: https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoMHMdQYzgOwGcAXMYgEzAF4wAeAFQD4AKABwEMAndgW0IC4wAb3YB+Qc2YBKaozD0pAGjAAjCa049B9MADJhYHIJKcAlvgDmYAL4yqcgG5xT5W7OHosXz3iKkLAKbEAPIqAFbUYNLuQp5gnEEArpz4BkZgAOQ47IkA1gCeGTae1p4+BCTxAYShETSBIeHS5X5ghBqRHNx8AHTsYKJgXbyEfdGCQqUYw70qzEI9iwk14cqLPe2ctqhTXtgU857s-NH2USKCGewAFnBhGbaKnmpRMxPpJuYWysdtxGaWNxnWLTLi8PobRIqEzMACMygATFIdjtkXtsOiwKhgMA2qYeKwYAFOGAAgAPXiEgJgAC0YAAYvAkOQ4NUwPg4KRCAFqQAiOCsYimAjsGCmYj5Xlgcxka7UmZBYlgdj4SjEOUJKBwBLS1Lq6kJYjJVIOUWJAK4CqkAXEAKUGgMCaqYz-L42Fg24X4cTyKTaPQGX6fSw2GKeQ3GjxYX4ZW0kDJPLDrZieghgAA+6eEjxKKMx6CAA

StackOverflow question: https://stackoverflow.com/questions/47024349/typing-result-of-optional-function-parameter-featuring-in-return-value

The problem I face is that I have a return value of a function depending on optional parameter which is of generic type. Simple example here:

```js

// simpler example - Flow does not see "optionality" in the parameter and therefore in the return value
const opted = (option?: T): T & { a: string } => {
return {
a: 'test',
...(option || {}),
}
}

// Flow error:
24: return { ^ object literal. This type is incompatible with the expected return type of
23: const opted = (option?: T): T & { a: string } => { ^ some incompatible instantiation of `T`
```

Flow seems to don't understand that `option` argument is optional therefore the result of the function is also "optional".

Any idea how to type such code?

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.