Hey, you got types in my JavaScript!

James Earl Douglas

May 26, 2020

Agenda

In the next ten 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, undefined, and throw.

Numeric product?

function multiply(x, y) {
  // implementation hidden
}

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...

function multiply(x: number, y: number): number {
  // implementation hidden
}

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 Monoid<A> {
  unit: A;
  concat(x: A, y: A): A;
}

Testable laws: identity, associativity

var multiplicationMonoid: Monoid<number> = {
  unit: 1,
  concat: (x: number, y: number) => {
    return x * y
  },
};
var multiply: (x: number, y: number) => number =
  multiplicationMonoid.concat;
var z: number = multiply(6, 7); // 42

\o/

It's complicated

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

multiply.ts:

var multiplicationMonoid: Monoid<number> = {
  unit: 1,
  concat: (x: number, y: number) => {
    return x * y
  },
};

var multiply: (x: number, y: number) => number =
  multiplicationMonoid.concat;

multiply.js:

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

Conclusion

Cons

Pros

References

Typescript

Software maintenance

Types and parametricity