TypeScript — JavaScript with superpowers — Part II

Welcome back to Part II! For a more articulated experience — read Part I first.

Enums (enumerations) allow you to group values together with friendlier names. Imagine you had a list of names.

Here’s how you would structure the enum:

You can grab the values from the enum like so:

But wait. It returns the integer which represents the index of the value. Like arrays, enums begin indexing their members starting at 0.

How do we get the value "Indrek" instead of 0 ?

Notice how the values are presented as a string.

Another great example would be using enums to store the application states.

In case you’re interested in learning more about enums— I found a great answer going in the nitty gritty of enum.

Let’s say we fetched some data from an API. We always expect the data to be fetched — but what if we can’t fetch the data?

Perfect time to return the never type (special case scenario):

Notice the error message we passed

We can call the error function inside another function (callback):

Notice how we don’t use the void but never since the inferred return type is never.

  • null — the absence of any value
  • undefined — a variable has been declared but has not yet been assigned a value

Not very useful on their own

By default null and undefined are subtypes of all other types. That means you can assign null and undefined to something like number.


Here’s a great post about null and defined by Dr. Axel Rauschmayer.

Type assertions usually happen if you know the type of some entity could be more specific than its current type.

Type assertions have no runtime impact, and is used purely by the compiler. TypeScript assumes that you, the programmer, have performed any special checks that you need.

Here’s a quick demonstration:

The bracket <> syntax collides with JSX so we use the as syntax instead.

Here’s a lot more about type assertions.

Cool stuff to consider

Now — build something awesome with Typescript!

Thanks for reading, hope you enjoyed and found it useful! Stay awesome!

Follow me on Twitter.