PubSub in TypeScript

October 2, 2012 · 2 minute read · typescript · javascript · web

Pub/Sub is my Hello World, I’ve done it not once but twice in JavaScript and once in CoffeeScript (although technically that has a 3rd version in JavaScript at the start of the post :P).

Well you may have heard of Microsoft’s answer to application-scale JavaScript called TypeScript so I thought I’d write a pub/ sub library in it too.

module PubSub {
    var registry = {}
    var pub = function(name: string, ...args: any) {
        if (!registry[name]) return;

            registry[name].forEach(x => {
                x.apply(null, args);

    var sub = function(name: string, fn: any) {
        if (!registry[name]){
            registry[name] = [fn];
        } else {

    export var Pub = pub;
    export var Sub = sub;

It’s pretty simplistic and I’ve gone with using the Array.forEach method rather than just a normal for loop for no reason other than I felt like it.

It could be used like so:

PubSub.Sub('foo', function (...args: any) {
     args.forEach(x => {
         console.log('argument', x);

PubSub.Pub('foo', 1, 2, 3, 4, 5);

setTimeout(() => {
    PubSub.Pub('foo', 'a', 'b', 'c');
}, 1000);

See, it’s just a pub/ sub library.

There is a few interesting thoughts here though:

  • function is not valid as an argument constraint
    • I’m assuming that’s just a limitation in the current compiler, you have to use any instead
  • They have splat support, ...args, which is another ES6 proposal and can be quite useful
  • I couldn’t work out how to define a class or interface to accurately represent what registry is, since it’s really an expando object
  • You always have to do export var <member name> = <what to export>, this annoyed me as I like to define everything up front and then later selectively export. I kept getting errors with export pub because I didn’t have a var in there


For me it’s pretty meh an experience. I’ve been doing JavaScript for long enough that the features added to language thus far aren’t a really compelling reason to go and write it over JavaScript.

What I have liked is the ability to use ES6 idioms (splats, modules, etc) is nice.

I’m curious to see what other things it will drive cough source maps cough in the future, but for the time being I’m not going to convert all my JavaScript files over.

Published: 2018-05-29 16:49:01 +1000 +1000, Version: aaf7f73