是否可以为现有类手动定义其他方法?
我的具体用例是bluebird的promisifyAll()
,其中:
通过遍历对象的属性并在对象及其原型链上创建每个函数的异步等价物来宣传整个对象... http://bluebirdjs.com/docs/api/promise.promisifyall.html
显然,流量无法自动解决这个问题。所以,我愿意帮助它。问题是如何?
考虑以下代码
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')
})
Flow在此处出现以下错误:
property `listenAsync`. Property not found in
Server
如果我使用listen
,则不会有任何错误。 flow非常聪明,可以看出这是模块中定义的真实方法。但listenAsync
是promisifyAll
的动态添加,对流
答案 0 :(得分:7)
这是不可能的,这样做并不安全。以下是您可以为您的案例做的事情:
首先声明bluebird
如下:
declare module "bluebird" {
declare function promisifyAll(arg: any): any
}
然后这样做:
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)
我们手动将http
投射到PromisifiedHttp
类型。我们仍然必须手动声明所有promisifed类型,尽管我们可以使用类型交集来扩展现有类型。