TypeScript — JavaScript with superpowers — Part II

03-09 07:26

TypeScript — JavaScript with superpowers — Part II

Welcome back, for more articulated experience — read the part I first .

Enums ( enum erations ) 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 enum — I found a great answer going in the nitty and 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 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! :orange_book:

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

标签: TypeScript JavaScript
© 2014 TuiCode, Inc.