# Using strongly typed events in TypeScript with interfaces (Part 2)

**Date:** 2016-03-26  
**Author:** Kees C. Bakker  
**Categories:** Strongly Typed Events, TypeScript  
**Original:** https://keestalkstech.com/using-strongly-typed-events-in-typescript-with-interfaces-part2/

![Using strongly typed events in TypeScript with interfaces (Part 2)](https://keestalkstech.com/wp-content/uploads/2016/03/lightning-bolt-1203953_1280.png)

---

In a [previous tutorial I explained how events can be implemented](https://keestalkstech.com/2016/03/strongly-typed-event-handlers-in-typescript-part-1/) as properties on a class using [Strongly Typed Events for TypeScript](https://github.com/KeesCBakker/Strongly-Typed-Events-for-TypeScript). Let's explore how to get events to work with interfaces.

Interfaces work a little different, because they don't have getters and setters on them (at least not in TypeScript 1.8).

## Interface implementation

Because interfaces don't support getter-properties, we'll need to use a method:

```ts
interface IClock {
    OnTick(): IEvent<IClock, number>;
}
```

## Class implementation

Now create a clock that takes a interval and fires a tick each interval.

```ts
class Clock implements IClock {
    
    private _ticks = 0;
    private _onTick = new EventDispatcher<IClock, number>();
    
    constructor(interval: number) {
        var _this = this;
        setInterval(function () { _this.Tick(); }, interval);
    }

    private Tick(): void {
        this._ticks += 1;
        this._onTick.dispatch(this, this._ticks);
    }

    //implement method by returning the dispatcher as
    //an IEvent to hide the dispatch method
    OnTick() {
        return this._onTick.asEvent();
    }
}
```

## Using the event handler

When the method is called an `IEvent` is returned. This event can be subscribed.

```ts
let clock: IClock = new Clock(5000);
clock.onTick().subscribe((sender, ticks) => alert('Tick-tock #' + ticks));
```

## More

Check out the following:
