Argument of type '(e: CustomEvent) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'

前端 未结 4 1084
执笔经年
执笔经年 2021-02-07 04:11

I have this custom event setup, and it works with TypeScript 2.5.3, but when I updated to 2.6.1 I get an error

window.addEventListener(         


        
4条回答
  •  执笔经年
    2021-02-07 04:52

    I created a generic function based off @jcalz's answer

    /**
     * Checks whether an object can be safely cast to its child type
     * @param parent the object to be 'narrowly' cast down to its child type
     * @param checkForProps props which aught to be present on the child type
     */
    export function isSubTypeWithProps(parent: P, ...checkForProps: (keyof C)[]): parent is C {
      return checkForProps.every(prop => prop in parent);
    }
    
    /**
     * Usage example
     */
    const el = document.getElementById('test');
    el.addEventListener('click', (e: Event) => {
      if (isSubTypeWithProps(e, 'which')) {
        if (e.which === 1) { // primary mouse button only ('which' prop is only available on MouseEvent)
          console.log('clicked');
        }
      }
    });
    

提交回复
热议问题