简体   繁体   中英

How to use RxJS fromEvent() with HammerJS in strict mode

The following code gives an error in typescript strict mode:

       const hammerTap = new Hammer(nativeElement, 
        {
            recognizers: [
                [Hammer.Tap, { taps: 4 }]
            ]
        });

        const tap$ = fromEvent(hammerTap, 'tap').pipe(share());

Argument of type 'HammerManager' is not assignable to parameter of type 'FromEventTarget<{}>'. Type 'HammerManager' is not assignable to type 'JQueryStyleEventEmitter'. Types of property 'on' are incompatible. Type '(events: string, handler: HammerListener) => void' is not assignable to type '(eventName: string, handler: Function) => void'. Types of parameters 'handler' and 'handler' are incompatible. Type 'Function' is not assignable to type 'HammerListener'. Type 'Function' provides no match for the signature '(event: HammerInput): void'.

The problem would only be truly fixable in @types/hammerjs , but you can do this:

const tap$ = fromEvent(<JQueryStyleEventEmitter> <unknown> hammerTap, 'tap').pipe(share());

or

const tap$ = fromEvent(hammerTap as unknown as JQueryStyleEventEmitter, 'tap').pipe(share());

JQueryStyleEventEmitter is defined as the following, and is part of RxJS, so don't worry - you're not including JQuery in any way shape or form.

export interface JQueryStyleEventEmitter {
    on: (eventName: string, handler: Function) => void;
    off: (eventName: string, handler: Function) => void;
}

You can also add <HammerInput> as a generic parameter to fromEvent , so the events coming back to you are of the correct type.

const panUnfilteredRaw$ = fromEvent<HammerInput>(hammerPan as unknown as JQueryStyleEventEmitter, 'panstart panmove panend').pipe(share());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM