-
Notifications
You must be signed in to change notification settings - Fork 1.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
node callbacks aren't defined quite right #2123
Comments
I've been looking for an answer to this question as well. I think the older discussion you may be referring to is #166 "Capture complete type of a node-style callback"? |
Following the intersection example I tried with type Callback<T> = ((error: Error) => mixed) & ((null, result: T) => mixed) but is does not work :( |
I tried: // @flow
type Callback = (...args: [Error] | [null, string]) => void;
function producer(callback: Callback) {
if (global.test) {
callback(new Error('error'));
} else {
callback(null, 'result');
}
}
function consumer() {
producer((err, result) => {
if (err) {
console.log(err);
} else {
console.log(result.length);
}
})
} But this still produces:
|
It's impossible to do this properly. This is the best solution at the moment: type Callback = (?Error, ?string) => void;
function producer(callback: Callback) {
if (global.test) {
callback(new Error('error'));
} else {
callback(null, 'result');
}
}
function consumer() {
producer((err, result) => {
if (err) {
console.log(err);
} else if (result) {
console.log(result.length);
}
})
} |
@vkurchatkin is correct. Currently there is not a great way to model this properly. Promises also help make this less of an issue 👍 |
This is still an issue and makes writing flowtype for Node-style callbacks cumbersome. The intersection example sounds like it should work, but it seems like flow isn't able to correctly match the two distinct signatures and verify them independently. |
The form used for the callbacks right now is generally along the lines of:
This works relatively well for most cases, but it breaks down if you write code that actually supports the node "errback" convention you run in to problems. A more accurate way to represent these callbacks would be something more like this:
Unfortunately, this doesn't seem to work out as well as advertised:
It would be nice if flow could treat the pair of arguments as a tagged/disjoint type so that flow could follow the branches and know that the error and success cases are mutually exclusive.
The text was updated successfully, but these errors were encountered: