简体   繁体   中英

is there any way we can define the types for the addEventListener and classList in a react typescript project

In our project(React with typescript) we are using the below code to add and manipulate the underline for the tabs in navigation bar.

public componentDidMount() {
        const tabs = document.getElementsByClassName("tab");

        Array.prototype.forEach.call(tabs, (tab: EventListener) => {
            tab.addEventListener("click", setActiveClass);
        });

        const setActiveClass = (event: any) => {
            Array.prototype.forEach.call(tabs, (tab: any) => {
                tab.classList.remove("active");
            });
            event.currentTarget.classList.add("active");
        };
    }.

The typescript is throwing following errors :
"[ts] Property 'addEventListener' does not exist on type 'EventListener'" and "[tslint] Type declaration of 'any' loses type-safety. Consider replacing it with a more precise type. (no-any)"

I would like to add appropriate types instead of using "any" in the code. I would also don't want to relax the tslint rule for "any"

Any help would be much appreciated.

Thanks

Using call is inherently not type safe. The definition of call will basically erase any function type information as it uses any :

call(this: Function, thisArg: any, ...argArray: any[]): any;

If you call forEach as a normal instance function the type of the parameter to the arrow function will be correctly inferred:

tabs.forEach(tab => {
    tab.addEventListener("click", setActiveClass);
});

const setActiveClass = (event: Event) => {
    tabs.forEach(tab => {
        tab.classList.remove("active");
    });
    if(event.currentTarget != null){
        (event.currentTarget as Element).classList.add("active");
    }
};

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