Pachari
Pachari

Reputation: 121

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?

Upvotes: 0

Views: 52

Answers (1)

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

enter image description here

Upvotes: 2

Related Questions