diff options
Diffstat (limited to 'test/test-types-compilation.ts')
| -rw-r--r-- | test/test-types-compilation.ts | 75 |
1 files changed, 55 insertions, 20 deletions
diff --git a/test/test-types-compilation.ts b/test/test-types-compilation.ts index 00510da..476e631 100644 --- a/test/test-types-compilation.ts +++ b/test/test-types-compilation.ts @@ -2,42 +2,77 @@ import mitt from '..'; -const emitter = mitt(); +interface SomeEventData { + name: string; +} + +const emitter = mitt<{ + foo: string; + someEvent: SomeEventData; + bar?: number; +}>(); + +const barHandler = (x?: number) => {}; +const fooHandler = (x: string) => {}; +const wildcardHandler = ( + _type: 'foo' | 'bar' | 'someEvent', + _event: string | SomeEventData | number | undefined +) => {}; /* - * Check that if on is provided a generic, it only accepts handlers of that type + * Check that 'on' args are inferred correctly */ { - const badHandler = (x: number) => {}; - const goodHandler = (x: string) => {}; + // @ts-expect-error + emitter.on('foo', barHandler); + emitter.on('foo', fooHandler); + emitter.on('bar', barHandler); // @ts-expect-error - emitter.on<string>('foo', badHandler); - emitter.on<string>('foo', goodHandler); + emitter.on('bar', fooHandler); + + emitter.on('*', wildcardHandler); + // fooHandler is ok, because ('foo' | 'bar' | 'someEvent') extends string + emitter.on('*', fooHandler); + // @ts-expect-error + emitter.on('*', barHandler); } /* - * Check that if off is provided a generic, it only accepts handlers of that type + * Check that 'off' args are inferred correctly */ { - const badHandler = (x: number) => {}; - const goodHandler = (x: string) => {}; + // @ts-expect-error + emitter.off('foo', barHandler); + emitter.off('foo', fooHandler); + emitter.off('bar', barHandler); // @ts-expect-error - emitter.off<string>('foo', badHandler); - emitter.off<string>('foo', goodHandler); -} + emitter.off('bar', fooHandler); + emitter.off('*', wildcardHandler); + // fooHandler is ok, because ('foo' | 'bar' | 'someEvent') extends string + emitter.off('*', fooHandler); + // @ts-expect-error + emitter.off('*', barHandler); +} /* - * Check that if emitt is provided a generic, it only accepts event data of that type + * Check that 'emit' args are inferred correctly */ { - interface SomeEventData { - name: string; - } - // @ts-expect-error - emitter.emit<SomeEventData>('foo', 'NOT VALID'); - emitter.emit<SomeEventData>('foo', { name: 'jack' }); -} + // @ts-expect-error + emitter.emit('someEvent', 'NOT VALID'); + emitter.emit('someEvent', { name: 'jack' }); + + // @ts-expect-error + emitter.emit('foo'); + // @ts-expect-error + emitter.emit('foo', 1); + emitter.emit('foo', 'string'); + emitter.emit('bar'); + emitter.emit('bar', 1); + // @ts-expect-error + emitter.emit('bar', 'string'); +} |
