简体   繁体   中英

Adding an EventListener with an function argument

I want to add an event listener to a button. The function which should be called on click gets passed as an argument. So it looks like this

public addButton(argFunction: Function) {
        const button: HTMLElement = document.createElement("button")

        button.addEventListener("click", argFunction);
    }

myclass.addButton(function(){
        console.log("test");
});

Trying to add the event listener this way results in TypeScript saying "The argument from type "Function" cannot get assigned to the parameter with Type "(this: HTMLElement, ev: MouseEvent) => any" (Roughly translated by me).

When i declare a function inside the addButton it works:

public addButton(argFunction: Function) {
        const button: HTMLElement = document.createElement("button")

        var f = function () {
            console.log("f")
        };

        button.addEventListener("click", argFunction);
    }

Why does this work and how can i pass a function as an argument?

Just use other type for your listener function:


type Listener = (ev: MouseEvent) => void

// alternative way
interface Listener2 {
  (ev: MouseEvent): void
}


class Foo {
  public addButton(argFunction: Listener) {
    const button: HTMLElement = document.createElement("button")

    button.addEventListener("click", argFunction);
  }
}
const foo = new Foo()

foo.addButton(function () {
  console.log("test");
});

Playground

Try to avoid capitalized constructor types like Function , String , Number , Object

In 99% cases it is better to use type Fn = (...args:any[])=>any instead of Function

I realized that types like String show errors instead of string. Is there a difference between them?

Yes, the is a difference. String , Number are constructor types, pretty much like Array . But when you create a simple string like foo , you don't use String constructor, like String('foo') . You just use literal foo .

Please see the docs

在此处输入图像描述

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