Friday, 20 September 2019

Type functions that can be promsified

I'm working on adding separate types to node-vagrant NPM library to use in Typescript, to be contributed under DefinitelyTyped. However, one of the methods of the library is promisify which makes all other functions then return a promise instead of a callback. What is the suggested method for typing this kind of dynamic action?

A minimal example would be for the JS file to be:

module.exports.foo = function (cb) {
    cb(null, 'foo');
};

module.exports.promisify = function () {
  module.exports.foo = util.promisify(module.exports.foo);
}

and the typing I've got is:

export function foo(cb: (err: null | string, out: string) => void): void;
export function promisify(): void;

Now, when I use the typings:

import foo = require('foo');

foo.foo((err, out) => { console.log(err, out); });
foo.promisify();
foo.foo().then(out => console.log(out)).catch(err => console.log(err));

where the last line throws an error with the TSC. Is the solution to just declare both callback and the promise on the function signature and have the end user appropriately decide on which one to use or is there some mechanism in TypeScript to dynamically toggle the return info on a function?

From the above, is the final verdict just doing:

export function foo(cb: (err: null | string, out: string) => void): Promise<string>;

and letting the end-user figure out if they want the callback or the promise?



from Type functions that can be promsified

No comments:

Post a Comment