Flowtype: dynamically expanding classes

Is it possible to manually define additional methods for an existing class?

My specific usecase is bluebird promisifyAll() , which:

Promotes the entire object by looking at the properties of the object and creating the asynchronous equivalent of each function of the object and its prototype chain ... http://bluebirdjs.com/docs/api/promise.promisifyall.html

Obviously, the thread will not be able to figure this out automatically. Therefore, I am ready to help. Question: HOW?

Consider the following code

 import http from 'http' import { promisifyAll } from 'bluebird' promisifyAll(http) const server = http.createServer(() => { console.log('request is in'); }) server.listenAsync(8080).then(() => { console.log('Server is ready to handle connections') }) 

The stream here contains the following error:

 property `listenAsync`. Property not found in Server 

There would be no error if I used listen . smart enough to see that this is the real method defined in the module. But listenAsync is a dynamic addition of promisifyAll and invisible to the thread

+6
source share
1 answer

This is impossible, and it would be unsafe. Here is what you can do for your case:

first declare bluebird as follows:

 declare module "bluebird" { declare function promisifyAll(arg: any): any } 

Then do the following:

 import httpNode from 'http' import { promisifyAll } from 'bluebird' import type { Server } from 'http' type PromisifiedServer = Server & { listenAsync(port: number, hostname?: string, backlog?: number): Promise<PromisifiedServer>; }; type PromisifiedHttp = { createServer(listener: Function): PromisifiedServer; }; const http: PromisifiedHttp = promisifyAll(httpNode) 

Here, we manually PromisifiedHttp http into the PromisifiedHttp type. We still have to declare all promisifed types manually, although we can use type intersection to continue existing types.

+7
source

All Articles