Blog

What The Heck Is TypeScript?

Now, as a prelude I want to let everybody know that I’m late to the party, as always. The only information that my brain captured about it over the years is that it, apparently, compiles to JavaScript. Why even do this? Why not just write JavaScript? To find out answers to my many questions, I set out sail to Google, obviously.

TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code.

Paul Dixon, explaining on Stack Overflow

Alright, so if I have an IDE that has support for TypeScript I apparently can write code much easier. Makes sense. And things are more concise, I guess. That’s cool. Is that it, tough? The answer is no. There’s more.

JavaScript is standardized through the ECMAScript standards. Not all browsers in use support all features of newer ECMAScript standards (see this table). TypeScript supports new ECMAScript standards and compiles them to (older) ECMAScript targets of your choosing (current targets are 3, 5 and 6 [a.k.a. 2015]). This means that you can use features of ES2015 and beyond, like modules, lambda functions, classes, the spread operator, destructuring, today.

Lodewijk Bogaards, explaining on Stack Overflow

Okay now it got me interested. Ability to use newer ECMAScript features while giving no regard to if browsers actually support them since it compiles to older JavaScript that works in most browsers anyway. That is super cool.

How do we actually use it?

Apparently it’s easier than you think. If you already have Node and npm installed on your machine, which you probably do if you’re reading this, then it is as simple as running the following line in your terminal:

npm install -g typescript

Once done, we can write a simple TypeScript file using whatever IDE you have. For example, let’s write the following code into a file we’ll name hello.ts.

function greeter(person: string) {
	
	return "Hello, " + person;

}

let user = "Jane Doe";

document.body.innerHTML = greeter(user);

Now to compile the hello.ts file to JavaScript we just run the following line in the terminal:

tsc hello.ts

And it should create a hello.js file in that same directory with pure JavaScript in it. Of course if you have an IDE that has support for TypeScript then you probably don’t need to touch the terminal to compile your code.

Conclusion

With the better debugging and the ability to use newer features of ECMAScript without worrying about browser support, I’ll try using TypeScript to write stuff in the future. It seems to have little value not to and I’m glad I have more or less caught up to this thing now. Even if I may be years late. I mean the thing is pretty awesome!