Skip to content

Commit cdc6c51

Browse files
wo-o29jungpaeng
andauthored
refactor: Improve type safety in createEmitter by removing non-null assertions (#202)
* refactor: improve type safety in createEmitter with nullish coalescing * changeset Refactor createEmitter to enhance type safety by eliminating non-null assertions. --------- Co-authored-by: Yongbeen Im <[email protected]> Co-authored-by: Yongbeen Im <[email protected]>
1 parent be20412 commit cdc6c51

File tree

2 files changed

+12
-7
lines changed

2 files changed

+12
-7
lines changed

.changeset/tiny-glasses-hammer.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"overlay-kit": patch
3+
---
4+
5+
refactor: Improve type safety in createEmitter by removing non-null assertions

packages/src/utils/emitter.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,37 +28,37 @@ export function createEmitter<Events extends Record<EventType, unknown>>(
2828
all?: EventHandlerMap<Events>
2929
): Emitter<Events> {
3030
type GenericEventHandler = Handler<Events[keyof Events]> | WildcardHandler<Events>;
31-
all = all || new Map();
31+
all = all ?? new Map();
3232

3333
return {
3434
all,
3535
on<Key extends keyof Events>(type: Key, handler: GenericEventHandler) {
36-
const handlers: Array<GenericEventHandler> | undefined = all!.get(type);
36+
const handlers: Array<GenericEventHandler> | undefined = all.get(type);
3737
if (handlers) {
3838
handlers.push(handler);
3939
} else {
40-
all!.set(type, [handler] as EventHandlerList<Events[keyof Events]>);
40+
all.set(type, [handler] as EventHandlerList<Events[keyof Events]>);
4141
}
4242
},
4343
off<Key extends keyof Events>(type: Key, handler?: GenericEventHandler) {
44-
const handlers: Array<GenericEventHandler> | undefined = all!.get(type);
44+
const handlers: Array<GenericEventHandler> | undefined = all.get(type);
4545
if (handlers) {
4646
if (handler) {
4747
handlers.splice(handlers.indexOf(handler) >>> 0, 1);
4848
} else {
49-
all!.set(type, []);
49+
all.set(type, []);
5050
}
5151
}
5252
},
5353
emit<Key extends keyof Events>(type: Key, evt?: Events[Key]) {
54-
let handlers = all!.get(type);
54+
let handlers = all.get(type);
5555
if (handlers) {
5656
(handlers as EventHandlerList<Events[keyof Events]>).slice().forEach((handler) => {
5757
handler(evt!);
5858
});
5959
}
6060

61-
handlers = all!.get('*');
61+
handlers = all.get('*');
6262
if (handlers) {
6363
(handlers as WildCardEventHandlerList<Events>).slice().forEach((handler) => {
6464
handler(type, evt!);

0 commit comments

Comments
 (0)