Hey, you got types in my JavaScript!

James Earl Douglas

June 23, 2015

Agenda

In the next five minutes, I aim to:

Types crypt

The fundamental problem addressed by a type theory is to ensure that programs have meaning.

-- Mark Manasse

Identity crisis

What does this function do?

function foo(x) {
  // implementation hidden
}

Parametricity

What does this function do?

function foo<A>(x: A): A {
  // implementation hidden
}

Possibilities Possibility

There's only one possible implementation*: identity.

function foo<A>(x: A): A {
  return x;
}
* If we ignore null and undefined.

Numeric product?

var z = multiply(6, 7);

What is z?

function multiply(x, y) { return x * y; } // 42
function multiply(x, y) { return x + y; } // 13
function multiply(x, y) { x * y; } // undefined
function multiply(x, y) { return x; } // 6
function multiply(x, y) { return 'lol'; } // 'lol'
function multiply(x, y) { } // undefined
function multiply(x, y) { return arguments[2]; } // undefined

╯°□°)╯︵ ┻━┻

Numeric product...

var z: number = multiply(6, 7);

Now what is z?

function multiply(x: number, y: number): number { return x * y; } // 42
function multiply(x: number, y: number): number { return x + y; } // 13
// function multiply(x: number, y: number): number { x * y; }
function multiply(x: number, y: number): number { return x; } // 6
// function multiply(x: number, y: number): number { return 'lol'; }
function multiply(x: number, y: number): number { return arguments[2]; } // undefined
// function multiply(x: number, y: number): number { return 'lol'; }

┬─┬ノ( º _ ºノ)

Numeric product!

interface Prod<A> {
  product(x: A, y: A): A;
}

function product<A>(p: Prod<A>): (x: A, y: A) => A {
  return p.product;
}

var numberProd: Prod<number> = {
  product: (x: number, y: number) => { return x * y },
};
var multiply: (x: number, y: number) => number = product(numberProd);
var z: number = multiply(6, 7); // 42

\o/

It's catchy

Web browsers don't know what TypeScript is. They need JavaScript.

$ tsc multiply.ts

multiply.js:

var numberProd = {
  product: function (x, y) { return x * y; }
};
function product(p) {
  return p.product;
}
var multiply = product(numberProd);

References

Typescript

Software maintenance

Types and parametricity