Stop the OO madness

Please stop the Java/C# Programming Paradigm for TypeScript

Wilfred Springer
Apr 5 · 2 min read

So, as announced, I started moving towards TypeScript. To be fair, for every line of TypeScript I write, I still spend an hour-and-a-half searching for alternatives that I might have missed out on, but I’m going there.

I was going through the TypeScript handbook, and one of the first things I stumbled across was something like this:

I got a rash the moment I noticed it. Not because of the type parameter. In fact, I added that myself. But because the validator really is just a single function. A single function to implement a particular strategy. If it’s just a singe function, then what’s the point of all the other boilerplate. Why add a method to a class?

I will tell you why. And this is one of the things bothering me about TypeScript: it’s because this is how it’s done in Java and C#. In JavaScript, and consequently in TypeScript, functions can be passed around, just as they are. There is no need to create instances of classes to pass some behavior around. You just pass the function itself around. In Java and C#, you can’t. So this is what you will find in Java and C# code. And now that programming style is getting pulled into JavaScript as well. The agony!

Now, this might seem a superficial and cosmetic issue only. But it isn’t. The JavaScript code generated will really construct a new instance of a class, making it more heavyweight than it needs to be.

I think the following should be considered the more idiomatic approach in the TypeScript world, and it certainly generates more idiomatic JavaScript code:

You still get all the compile time enforcement you need: if you have a component expecting a Validator<String> then you can pass in validZip, but you won’t be able to pass in (b: boolean) => true since that’s a Validator<Boolean>.

East Pole

Distributed reflections of the third kind

Wilfred Springer

Written by

Double bass playing father of three, hacker and soul searcher

East Pole

East Pole

Distributed reflections of the third kind

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade