Telerik blogs
JavaScriptT Light_870x220

TypeScript is the cool (new? sort-of) kid on the block. In this article, we will explore the basics of "types," the core feature this superset gives us - and why you may care about joining in on all the funz.

So maybe you’ve heard about this thing called TypeScript. Maybe you haven’t – maybe you live in a pineapple under the sea or are still hacking away at ActionScript 2. Regardless, TypeScript is a thing, it’s happening, it’s here to stay, and it’s gaining strength by the minute.

Let’s dive in on the very basics.

Type-Script?

So what exactly -is- TypeScript (TS for short)?

TypeScript is a typed superset of JavaScript that compiles to JavaSscript.
-Microsoft

Ok so, that’s a bunch of fancy terms to say, that it’s an evolved form of JS. A superset language is a language that is built on TOP of the other one, so sort of like a Pokemon evolution without all the pretty graphics and cuteness.

You get all that is JavaScript, plus a little extra.

What about the typed part? It means that TypeScript allows you to basically tell your computer, when you’re coding, what each part of your code will hold. Think of it as putting labels on your variables and functions to make them strict on what they should be doing or containing.

Ok so, what about the compiles to JavaScript? Well, currently TypeScript is not something that browsers can understand. Browsers speak JavaScript. So when you work with this superset, you are going to have to use some sort of tool to change it back to JavaScript before you deploy.

This all sounds super scary? Maybe. Ever worked with SCSS? Aha! Well, that’s another superset but for CSS. 😉

Let’s talk Moneyz

Variables in JavaScript don’t have types. This means you can basically put anything and everything you want into a variable and it’s completely valid code. For example:

let myBox = 'This would be a string';
myBox = 23; // But now it's a number
myBox = { box: true }; // I can also put objects
myBox = [ 'there is no other like it', 'and this one is mine' ]; // and arrays :)

This code above is completely valid JavaScript code, a variable can change its contents as needed because the box (variable) that contains this content is flexible and will adjust to whatever you pass to it.

Sweet, ok, but why would I want to lose this flexibility?

We’ve all run into a scenario where something like this happens. You have a variable, which is a number, let’s say it’s the user’s bank account moneyz.

let moneyz = 20; // Yes, this is how I spell it, let me be

So far so good, but maybe you make a call somewhere that is going to tell you how much money was just deposited into the account. But something somewhere in the land of “omg how am i going to debug this” made the second value a STRING.

So you merrily code a function:

function incrementMoneyz(oldMoneyz, newMoneyz) {
  return oldMoneyz + newMoneyz;
}

However in reality now you have a case where, say, you’re adding up a number and a string. So the 20 she had before, added to the “20” she just deposited into her account…

let moneyz = 20;
let deposit = "20";
let moarMoneyz = incrementMoneyz(moneyz, deposit); // Result => "2020"

Now, TypeScript is not going to protect you from runtime bugs and wild APIs, because in the end when you deploy your code it’s going to be good old JavaScript. But if this error is happening because of some oversight in your code, TypeScript is going to yell at you and hopefully prevent this mistake from happening.

So how then, do we set types on our variables?

Type-Proofing

Super simple, let’s learn by example. Switch gears to TypeScript (TS from now on, fingers hurt).

// This is TYPESCRIPT
let number = 20;
number = '20'; // ERROR

In TS, the compiler checks your code like big brother. So, in the above example, you are declaring a number variable old-school, no type. However, TS will know and label this variable as a Number. Why? Because you’re putting a number in it initially!

So what’s going to happen is that when you compile this code, TS will throw an error because '20' is not a number, it’s a string.

Simple, right? This type of, well… type… is called an inferred type. That mean’s you’re leaving TS all the heavy lifting.

What if, however, we want to keep all the control of types for ourselves? Then we have to explicitly tell TS what we want.

let typedNumber: number = 20;
typedNumber = '20';

Same example, but I switched the variable name to typeNumber for clarity.

See the : number part after the variable declaration? That’s the actual type! It reads:

I want a new variable, called typedNumber, with a type of a number value, and the initial value is 20.

When the compiler hits the second line, and sees the string, it will also complain and throw and error - as expected.

Numbers, check. What other types are there though?

Booleans

let myBool: boolean = false;


let emptyBool: boolean; // Yup, you can declare it without initial value!
emptyBool = 'false'; // Error, emptyBool has a type of boolean!

Strings

let myString: string = 'TS is bae';
myString = ['EVIL']; // Error! myString is typed as string


let quotes: string = "You can also use double quotes :)";


let awe: string = ":o"
let backtick: string = `And backticks! ${awe}`;

Arrays

let anArrayOfNumbers: number[] = [1,2,3];
let alsoAnArrayOfNumbers: Array<number> = [1,2,3];


let anArrayOfStrings: string[] = ['a','b','c'];
let alsoAnArrayOfStrings: Array<string> = ['a','b','c'];

Arrays have a little gotcha to how they’re typed, because as you can see from the above example, we have two different syntaxes. In the first one, we tell the compiler the contents of the array plus []. On the second syntax, we first say it's an Array and then what’s going to be in it.

Feel free to use whichever works better for you.

Tuple

So what is a Tuple?

Simply put, a Tuple is an array of a defined/fixed number of elements which you know what they are beforehand, and that have different types.

This is best explained with an example. Imagine you have an API for users, which you know returns an array with the name at index 0, the last name at index 1, and the age at index 2.

// ['Marina', 'Mosti', 32];


let userTuple: [string, string, number];
userTuple = ['Daenerys', 'Targaryen', 17]; //This is valid. Also. How you doin'?
userTuple = ['Sansa', 'Stark', 'IDK kill her already']; // This would be an error

Keep in mind that although Tuples are super useful, they are only to be used in the particular cases where you know that your data is going to have this format, because even a simple thing like a change in array index will break the type.

Enum

Enum is another new datatype in TypeScript that we get to play with.

Ever been in a scenario where you want to define a list to just make some reference later on, and you end up doing a bunch of constant literal strings to keep track of it?

Take for example a user’s membership to a site, which has a few defined options.

enum Membership { Free, Member, Gold   }

The enum here is just defining a list. This is not a variable - imagine that you’re only making the blueprint for this type.

Now to actually use it, we could do the following:

enum Membership { Free, Member, Gold   }


const userMembership: Membership = Membership.Free;

Take a look at the const variable that we’re setting up. The type is actually Membership, which is referencing the enum that we created before. This way, we can actually access Membership.Free and set it to this variable.

Keep in mind something important: The actual value of the variable is a number! The enum actually behaves like an array, where each item gets a 0 index incremental value. You can also override these internal values by setting them with an equal sign.

enum Membership { Free = 3, Member, Gold   }

In this case, Member would be 4, and Gold would be 5 - they increment starting from the last known value, in this case 3, defined by Free.

But, I’m a Free Spirit!

So you may argue at some point that not having types is actually a benefit. That you prefer your functions be be able to return 3 different types of data depending on output. That you will not succumb to these chains!

Good news! There's one more datatype for specially this type of situation: Any

As the name already tells you, this type makes the variable behave in the same way that plain JavaScript does.

const anarchy: Any = 'YAAAAS';
anarchy = 9000; // works! :)

Wrapping Up

TypeScript is coming with force into the FE dev world, if you have been putting it on hold to start playing with it and learning, now is the time to pick it up and start polishing your typed-skills.

If you want to read/learn more about I recommend diving into the handbook and tutorials they have up in their official website.

Thanks for reading!


This post has been brought to you by Kendo UI

Want to learn more about creating great web apps? It all starts out with Kendo UI - the complete UI component library that allows you to quickly build high-quality, responsive apps. It includes everything you need, from grids and charts to dropdowns and gauges.

KendoJSft


About the Author

Marina Mosti

Marina Mosti is a frontend web developer with over 18 years of experience in the field. She enjoys mentoring other women on JavaScript and her favorite framework, Vue, as well as writing articles and tutorials for the community. In her spare time, she enjoys playing bass, drums and video games.

Comments

Comments are disabled in preview mode.