refactoring

This commit is contained in:
Philipp Kühn 2021-09-30 09:34:45 +02:00
parent 54e85fd284
commit 8db5a943d2
3 changed files with 16 additions and 9 deletions

View File

@ -23,7 +23,8 @@ import {
CanCommands,
ChainedCommands,
SingleCommands,
TextSerializer, EditorEvents,
TextSerializer,
EditorEvents,
} from './types'
import * as extensions from './extensions'
import style from './style'

View File

@ -1,12 +1,18 @@
type StringKeyOf<T> = Extract<keyof T, string>;
type CallbackType<T extends Record<string, any>, EVENT extends StringKeyOf<T>> = T[EVENT] extends any[] ? T[EVENT] : [T[EVENT]];
type CallbackFunction<T extends Record<string, any>, EVENT extends StringKeyOf<T>> = (...props: CallbackType<T, EVENT>) => any
type StringKeyOf<T> = Extract<keyof T, string>
type CallbackType<
T extends Record<string, any>,
EventName extends StringKeyOf<T>,
> = T[EventName] extends any[] ? T[EventName] : [T[EventName]]
type CallbackFunction<
T extends Record<string, any>,
EventName extends StringKeyOf<T>,
> = (...props: CallbackType<T, EventName>) => any
export default class EventEmitter<T extends Record<string, any>> {
private callbacks: { [key: string]: Function[] } = {}
public on<EVENT extends StringKeyOf<T>>(event: EVENT, fn: CallbackFunction<T, EVENT>): this {
public on<EventName extends StringKeyOf<T>>(event: EventName, fn: CallbackFunction<T, EventName>): this {
if (!this.callbacks[event]) {
this.callbacks[event] = []
}
@ -16,7 +22,7 @@ export default class EventEmitter<T extends Record<string, any>> {
return this
}
protected emit<EVENT extends StringKeyOf<T>>(event: EVENT, ...args: CallbackType<T, EVENT>): this {
protected emit<EventName extends StringKeyOf<T>>(event: EventName, ...args: CallbackType<T, EventName>): this {
const callbacks = this.callbacks[event]
if (callbacks) {
@ -26,7 +32,7 @@ export default class EventEmitter<T extends Record<string, any>> {
return this
}
public off<EVENT extends StringKeyOf<T>>(event: EVENT, fn?: CallbackFunction<T, EVENT>): this {
public off<EventName extends StringKeyOf<T>>(event: EventName, fn?: CallbackFunction<T, EventName>): this {
const callbacks = this.callbacks[event]
if (callbacks) {

View File

@ -140,9 +140,9 @@ export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) ex
export type Diff<T extends keyof any, U extends keyof any> =
({ [P in T]: P } & { [P in U]: never } & { [x: string]: never })[T]
export type Overwrite<T, U> = Pick<T, Diff<keyof T, keyof U>> & U;
export type Overwrite<T, U> = Pick<T, Diff<keyof T, keyof U>> & U
export type ValuesOf<T> = T[keyof T];
export type ValuesOf<T> = T[keyof T]
export type KeysWithTypeOf<T, Type> = ({ [P in keyof T]: T[P] extends Type ? P : never })[keyof T]