Issue
i want to to add options to scroll event of an element in TypeScript like this:
element.addEventListener("scroll", () => { }, { capture: true, passive: true });
But TypeScript throw an syntax error: Argument of type '{ capture: true, passive: true }' is not assignable to parameter of type 'boolean'.
I know the reason of error is TypeScript does not define an options argument for addEventListener. It just only have useCapture argument. We can see it in lib.dom.d.ts:
addEventListener<K extends keyof ElementEventMap>(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
I found an open issue and a walk around in github but it seems complicate and i am not sure it is right.
By the way, i also want to know why TypeScript did not define options argument for addEventListener?
Any help would be appreciated. Thanks!
Solution
As a workaround for situations like this, you can always cast your object to the any type.
(<any>element).addEventListener("scroll", () => { }, { capture: true, passive: true });
The any type is used to opt-out of typescripts typing system. Meaning you will work on an unknown type that you can treat any way you like, without the typescript compiler complaining.
You can read more on the any type here!
Answered By - Fredrik Lundin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.