创建一个继承自 EventEmitter 的函数
Create a function that inherits from EventEmitter
使用 TypeScript,有没有办法声明一个继承自 EventEmitter 的函数(不是 class)?
使用 vanilla JS 是可行的,但不确定如何使用 TS 实现。
export const foo = function extends EventEmitter(){ // lol no
return {}; // (I need to return something here)
};
这是你如何用 JS 实现它的(我上次检查过):
const p = Object.assign(Object.create(Function.prototype), EventEmitter.prototype);
Object.setPrototypeOf(foo, p);
如果我尝试用 TS 来做,我会得到这个 problem/error:
既然你想手动将函数变成别的东西,那么你也需要手动转换它:)
import { EventEmitter } from "events";
function target(emitter: EventEmitter){
emitter.on('foo', ()=>{})
console.log(emitter.on);
}
let f = function f(){}
const casted = Object.assign(f.prototype, EventEmitter.prototype) as EventEmitter
target(casted);
为了正确地做到这一点并让 TypeScript 发挥良好的作用,我们创建了一个具有正确签名的辅助函数:
import EventEmitter = NodeJS.EventEmitter;
export interface FunctionEmitter extends Function, EventEmitter {
}
export const makeFunctionEmitter = function (fn: Function): FunctionEmitter {
const p = Object.assign(Object.create(Function.prototype), EventEmitter.prototype);
Object.setPrototypeOf(fn, p);
EventEmitter.call(fn);
return fn as FunctionEmitter;
};
那么我们就这样使用它:
export interface MyActualType extends FunctionEmitter{
(a: string, b: boolean, c: number): X
}
export const myFuncEmitter = makeFunctionEmitter(<MyActualType >function(a,b,c){
return X;
});
使用 TypeScript,有没有办法声明一个继承自 EventEmitter 的函数(不是 class)?
使用 vanilla JS 是可行的,但不确定如何使用 TS 实现。
export const foo = function extends EventEmitter(){ // lol no
return {}; // (I need to return something here)
};
这是你如何用 JS 实现它的(我上次检查过):
const p = Object.assign(Object.create(Function.prototype), EventEmitter.prototype);
Object.setPrototypeOf(foo, p);
如果我尝试用 TS 来做,我会得到这个 problem/error:
既然你想手动将函数变成别的东西,那么你也需要手动转换它:)
import { EventEmitter } from "events";
function target(emitter: EventEmitter){
emitter.on('foo', ()=>{})
console.log(emitter.on);
}
let f = function f(){}
const casted = Object.assign(f.prototype, EventEmitter.prototype) as EventEmitter
target(casted);
为了正确地做到这一点并让 TypeScript 发挥良好的作用,我们创建了一个具有正确签名的辅助函数:
import EventEmitter = NodeJS.EventEmitter;
export interface FunctionEmitter extends Function, EventEmitter {
}
export const makeFunctionEmitter = function (fn: Function): FunctionEmitter {
const p = Object.assign(Object.create(Function.prototype), EventEmitter.prototype);
Object.setPrototypeOf(fn, p);
EventEmitter.call(fn);
return fn as FunctionEmitter;
};
那么我们就这样使用它:
export interface MyActualType extends FunctionEmitter{
(a: string, b: boolean, c: number): X
}
export const myFuncEmitter = makeFunctionEmitter(<MyActualType >function(a,b,c){
return X;
});