我想给 callable object 加上 function 类型提示
// refer to: https://medium.com/@adrien.za/creating-callable-objects-in-javascript-fbf88db9904
class Callable extends Function {
constructor() {
super('return arguments.callee._call(...arguments)')
}
}
class AjaxFactory extends Callable{
constructor(){
super()
}
_call(url:string, init?:RequestInit) {
//middleware(init)
return fetch(url, init)
}
//use(middleware){...}
}
每次创建新对象时,调用方总是要类型转换一下,才能获得类型提示
type AjaxFactoryF = AjaxFactory & AjaxFactory['_call']
const request=<AjaxFactoryF>(new AjaxFactory()) //使用方要进行一下类型转换
//request.use(middleware)
request('http://x.com').then(resp=>console.log(resp))
有办法简化吗?隐式修改 class constructor 的类型?
1
a132811 OP 可加一个 alias 中间变量:AjaxFactoryAlias ,给中间变量带上扩展的类型 AjaxFactoryF
type AjaxFactoryF = AjaxFactory & AjaxFactory['_call'] const AjaxFactoryAlias = AjaxFactory as new ()=>AjaxFactoryF export {AjaxFactoryAlias as AjaxFactory} |