Typescript signatures and category theory

391 views Asked by At

I'm wondering if TypeScript right now is expressive enough to model some typical category theory type signatures.

For example, I may have a functor type defined as (I'm using Fantasy Land version of Damas–Hindley–Milner type signatures):

fantasy-land/map :: Functor f => f a ~> (a -> b) -> f b

Initially, I thought I could model it with a TypeScript interface:

export interface Functor<A> {
  ["fantasy-land/map"]<B>(f: (source: A) => B): Functor<B>;
}

Which works well enough:

class Identity<A> implements Functor<A> {
  constructor(private value: A) {}
  ["fantasy-land/map"]<B>(f: (source: A) => B): Functor<B> {
    return new Identity(f(this.value));
  }
}

But here's the problem: the return type is not Identity<B>, but Functor<B>.

Using this type signatures sounds like the right way, but this way I can only return Identity<A> and not Identity<B>.

So, it sounds to me like TypeScript does not have the means to express this kind of typing faithfully. Am I missing something or is it so?

0

There are 0 answers