생성자에서 타입정의

일반적인 Node.js와 전통 JavaScript에서는 단일 이벤트 출력기를 사용합니다. 이 이벤트 출력기는 내부적으로 여러 이벤트 종류에 대한 리스너를 관리합니다. 예를 들어:

const emitter = new EventEmitter();
// Emit: 
emitter.emit('foo', foo);
emitter.emit('bar', bar);
// Listen: 
emitter.on('foo', (foo)=>console.log(foo));
emitter.on('bar', (bar)=>console.log(bar));

기본적으로 EventEmitter 내부에는 데이터가 매핑된 배열로 저장됩니다:

{foo: [fooListeners], bar: [barListeners]}

대신, 순전히 이벤트 타입 안전성을 위해 이벤트 타입별로 출력기를 만들 수도 있습니다:

const onFoo = new TypedEvent<Foo>();
const onBar = new TypedEvent<Bar>();

// Emit: 
onFoo.emit(foo);
onBar.emit(bar);
// Listen: 
onFoo.on((foo)=>console.log(foo));
onBar.on((bar)=>console.log(bar));

이렇게 하면 다음과 같은 장점이 있습니다:

  • 이벤트의 타입이 변수 값을 통해 쉽게 파악됨.

  • 이벤트 출력기 변수를 독립적으로 손쉽게 리팩토링할 수 있음.

  • 이벤트 자료 구조의 타입 안전성.

TypedEvent 예시

Last updated

Was this helpful?