Why I choose Typescript: Specifying generic parameters during call-time.

Nadeesha Cabral
2 min readJul 2, 2017

--

Example of a Typescript-based Relay QueryRenderer Wrapper’s signature from one of my side projects

I’ve had time to sink my teeth into both Flow and Typescript, having built Saul with flow and working with Typescript based projects over the last year.

Warning: Please take what follows with grains of salt. Bias is strong here.

Specifying generic parameters during call-time was the single biggest issue for me when I was dealing with flow, after coming from a Typescript background. Here’s an example of this.

Example usage of callable generics

I very much rely on refining my generic parameters during the call time — as would any developer who relies on making use of generics heavily. In the real world, I found not having this ability to be a dealbreaker when working with higher-order functions and functional composition.

In a nutshell, if I could send a bunch of generic arguments to a function that can give me a response based on those generic arguments, the type system should give me the option of narrowing down the probability space of those generics in every use of the function. Typescript does that, whereas flow does not.

Suppose I have a higher order function definition, like this (this is a real example from one of my projects where this was a higher order react component):

Put simply, this will take all the props OwnProps I pass here, and `assign` a user prop to it.

Let’s consider invoking this with flow:

And now with Typescript:

As you can see, Typescript will mark my exported type as something that has the props of IPageProps and the wrapped component as something which will have the user: IUser as a prop.

In flow, I have be explicit and annotate the type of AuthenticatedPage.

This is a bigger deal that HOCs (Higher-order components) though. When using libraries that allow function chaining/composition such as lodash, ramda, immutable, etc, it helps a lot to refine your types along the chain.

Note: This is valid at the time of writing. It’s possible that flow will add support for this in future. But this is something that made me convert an entire React project from flow to typescript, at the time of writing.

--

--

Nadeesha Cabral

Hi, I’m Nadeesha. I work with computers a lot. I write about software development, and a few other things.