Why Types? For JavaScript developers
I’ve been rewatching the Ultimate Angular TypeScript fundamentals course over the last few days. And it’s made me think about types, what benefit they bring. Before I was a JavaScript developer I did a few years as a .Net developer, using C#. So the concept of types wasn’t completely new to me when I started working with Angular and TypeScript. I was used to the idea of interfaces, and classes. I’d actually spent many years learning OOP, first with ColdFusion and then with C#.
When going through the TypeScript course and with the work I’ve been doing with TypeScript, I was thinking of how I would explain to a JavaScript developer, someone who’s mainly been using jQuery why using Types and in particular TypeScript is a good thing.
As I see it there are two great reasons for Types, first by using types within your code, you are in a way ‘describing’ your code. For example, if you are creating a function that takes in two properties. Normally in JS you’d just past them in, all you’d know is their name, you don’t know ‘what’ they represent. Now with typescript, you can create object/types that describe what is being passed in. No more of this duck typing, where you are just throwing properties around not too sure what they actually are. So the first reason I think types are great is they give you this descriptive nature within your code. When you read TypeScript you know what the types of the properties being passed into a function are.
So as well as this descriptive nature that types give you, the other reason I think Types are such a great thing for JS developers is, by describing your code and creating types you can write code that the JavaScript engine can use to make extremely fast and optimised code. Code that can ‘tell’ the JavaScript engine what things (properties etc) are. The more information you can give the JS engine the better it’ll run.
Now, this isn’t just something I believe, it’s based on a talk I watched on how JavaScript engines actually work. There is a talk by Franziska Hinkelmann at JSConf, where she explains how the V8 JavaScript engine works. In this talk, Franziska shows that by using types to tell the JS engine all about your code the JS engine will run faster, be more optimised. But don’t take my word for it watch Franziska fantastic talk