Most developers (myself included) look at JavaScript and don’t tend to think twice about the code we produce. This is commonplace amoungst us all that with a little love and care any amount of code can be made to work the way we need it to.

Except we tend to make assumptions, and this is where good old vanilla JavaScript tends to let us and our fellow developers down.

With TypeScript, this problem of making assumptions and blind guesses are removed through the power of static analysis. Why though?

TypeScript is a statically typed subset of JavaScript which means that it implements all the goodness that we are used to right now without the need to learn a completely new language. TypeScript offers us a new way of simplifying our code and bringing new intellisense features not truly available to JavaScript that impowers us to build better and higher quality code.

Why Should You Use TypeScript?

Many different reasons exist for this question but I will give mine.

TypeScript eliminates the vast majority of assumptions we as developers make on a daily basis, it improves our communication skills through code and provides abstraction and granularity that isn’t possible with vanilla JavaScript.

That said, everyone has their own reasons for wanting or needing to use TypeScript and for me the decision to switch was pretty simple.

Originally, I jumped on the TypeScript hype train all the way back in late 2012-early 2013 but at that time it wasn’t matured enough and I went back to my existing ways of writing code without second guessing myself.

Jumping to 2015, I rediscoverd TypeScript and what a difference two years made. It had matured into and blossomed into a truly extraordinary addition to ECMAScript.

Getting Started

Microsoft over the years have done an amazing job at supporting the open source community and by doing so have allowed TypeScript to be integrated into a vast array of IDE’s OOTB. Here’s a few:

  1. Visual Studio Code
  2. Visual Studio 2017+
  3. WebStorm
  4. Sublime Text

Even if your IDE supports TypeScript natively, it is a good idea to install it at a system level too on the off-chance that you want to use a different version to what is bundled with your IDE. This can be done by running the following command in your terminal.

npm install -g typescript

The Basics

Lets start with a simple hello function.

function sayHello(name) {
  name = name || 'Chris'
  console.log('Hello,', name)
}

There isn’t a whole lot going on here, we have a name parameter, a default check incase name turns out to be falsey and a console.log statement. It is at this point that a good portion of developers I have met along the way struggle with as they believe this code is rock-solid.

Let’s go over a couple of possible problems:

  1. We assume that the type for name is a String
  2. Any value can be passed through as the name

We can easily get around this by doing some static analysis on-the-fly but that means more code to write. With TypeScript, this isn’t an issue as it can prevent us from making assumptions that don’t need to be.

NOTE: From here on out I will be making use of ES6, for a basic rundown please see Getting Started with ES6.

function sayHello(name: string = 'Chris') {
  console.log('Hello,', name)
}

To understand what is going on lets have a look at another example using the above function which triggers a TypeScript error.

sayHello(1)
// Argument of type '1' is not assignable to parameter of type 'string'.

What happened here is that TypeScript made an assertion about what type our name parameter needs to be. It took that result and with a little bit of magic that tells us that the type number is not assignable to the type string. This is amazing because now it means our previous assumptions are gone and we have clean and self-documenting code that is more intuitive and easily sharable.

If this is all TypeScript did then it would be a pretty boring article but there is so much more.

Optional parameter with fallback

This example outlines our original example by which we checked if name has a truthy value but now we get type checking too so we remain type-safe.

function sayHello(name?: string) {
  console.log('Hello,', name || 'Chris')
}

sayHello()      // Valid      -> 'Hello, Chris'
sayHello('Foo') // Also valid -> 'Hello, Foo'

Explicit return type

One of the more useful parts of any language is knowing what a function returns back to you. Our function becomes more robust and intutitive.

function multiply(num: number): number {
  return num * 2
}

// Valid
const doubled: number = multiply(2)

// Invalid
const doubled: boolean = multiply(2)
// Type 'number' is not assignable to type 'boolean'.

Accepting specific objects

function sayHello(person: { name: string }) {
  console.log('Hello', person.name)
}

// Valid
sayHello({ name: 'Chris' })

// Invalid
sayHello({ foo: 'Chris' })
// Argument of type '{ foo: string; }' is not assignable to parameter of type '{ name: string; }'.
// Object literal may only specify known properties, and 'foo' does not exist in type '{ name: string; }'.

Plently More Fun

There are a metric boatload of other awesome things that TypeScript allows us to accomplish but for now I will leave it here. If you enjoyed getting to know TypeScript from a very basic level then I recommend going through the documentation which provides many awesome examples.

The takeaway I want for you is to have a profound understanding of the absolute basics, there are tonnes of different way to use TypeScript but keeping things simple at first is always best.

I hope you enjoyed this and thank you for reading!