An Introduction to TypeScript

You can access the full course here: TypeScript for Beginners

Part 1

In this course, we’re going to learn the ins and outs of TypeScript.

About TypeScript

TypeScript is a superset of Javascript.  This means that while Javascript is valid TypeScript, TypeScript is not valid Javascript and has to be transpiled to be compatible with browsers.  However, TypeScript offers numerous benefits like IntelliSense and other features that help catch code errors.

Downloading Necessary Programs

We’ll first begin by downloading and installing necessary programs for this course.  Head over to the node.js website (https://nodejs.org/en/) to grab the first program.  Select the “LTS” option to download it while making sure you get it for the right operating system.  Once downloaded, double click the download to install it.

Node.js homepage with 8.11.1 LTS version

Next, we need to install TypeScript.  Since node.js comes with npm, or node package manager, we can install it via Terminal on Mac or Command Prompt on Windows.  You can find the code you need on the TypeScript website (https://www.typescriptlang.org/) in the download section.

TypeScript command prompt install instructions on website

Once you have the code, open Terminal or Command Prompt.  Paste the code in and hit enter to install the package.

npm install -g typescript

Last but not least, we need to grab a code editor.  For this course, we’ll be using Visual Studio Code.  On the website (https://code.visualstudio.com/), hit the download button for the appropriate version for your operating system.  Then, double click the downloaded file to install it.

Visual Studio Code homepage with Download button circled

In the next lesson, we’ll start working with TypeScript.

Part 2

In this lesson, we’re going to start working with TypeScript in our code editor.

Finishing Setup

Open up Visual Studio Code if you haven’t already.  Before making any files, we need to install an extension for TypeScript.  On the left column in Visual Studio Code, you can bring up the extensions list via the last item in the column.  Type in “Typescript” to find available extensions and install TypeScript Hero.

TypeScript Hero extension in VS Code

Once installed, head back into the home file area of of Visual Studio Code.  In the Code dropdown area, select the paper icon to create a new file.  You may also right click to create the file.  We will name this file main.ts.  Make sure to put any coding you write along with us in this file.

VS Code with arrow pointing to New File button

About Variables

While in Javascript the standard is to use var to declare variables, in TypeScript we want to use let and const. This is largely due to the scope.  While var is scoped to the function, let is scoped to the code block making it less hazardous.  Const, as the root implies, is a variable that is read-only, thus protecting the variable from change.

export {};

var a = 10;
let b = 10;
const c = 10;

(Note: For now, we need to add export at the beginning of the file to prevent the program from throwing errors.)

With TypeScript, we also assign data types that the variable can accept.  For example, in the code below we specify d can accept a number.  However, by trying to assign a string to the variable, we’re told this is incompatible.

export {}

let d: number;

d = 'hello';

main.ts showing data type error

For the data type, we can declare it as a number, string, boolean, or any. Any is used when the expected value is an unknown type.  Regardless of type, this feature is beneficial for catching certain errors with variable assignment.

Quickly, another feature of TypeScript comes with strings.  With strings, we can use backticks to put our string onto multiple lines.

b = `
    Hello World
    From a multiline!
`;

Transpiling

Let’s try out transpiling our code.  Back in Terminal or Command Prompt, we can enter the following line (which you can find partly from the TypeScript website: https://www.typescriptlang.org/) to transpile our main.ts file.

tsc --target ES2016 ./main.ts --watch

Back in Visual Studio Code, you will see that we now have another file that’s in Javascript.

VS Code showing main.js and main.ts

You can also leave off the target portion of the command, which automatically converts the code via ES5.

main.js as it appears after being transpiled from TypeScript

All in all, TypeScript offers us easy to use and convenient features we can utilize.  Next lesson, we’ll talk more about variables.  If you’d like to learn more about the basic declarations, though, you can check out the TypeScript documentation for them: https://www.typescriptlang.org/docs/handbook/variable-declarations.html

Part 3

In this lesson, we’re going to work on more advanced types of variables in TypeScript.

Arrays & Tuples

We’ll first take a look at an array.  Like other variables, we can assign the array a type so that it checks to make sure additions to it suit that type.  In the example below, while the syntax is different, the two arrays are functionally the same.

export {};

let stringArr: string[];
stringArr = ['hello', 'world'];

let genericArr: Array<string>;
genericArr = ['hey', 'hello'];

By transpiling the code, you can see both arrays are changed to the same syntax in Javascript.

Transpiled arrays from TypeScript showing same in JavaScript

Let’s say you needed an array like object that could allow for all sorts of data types.  For this, we can use tuples.  In tuples, we can specify multiple types it can accept.

let myTuple: [number, boolean];
myTuple = [3, true];

To learn more about arrays and tuples, please refer to the TypeScript documentation: https://www.typescriptlang.org/docs/handbook/basic-types.html

Enumerators

TypeScript also allows for enums, which let us declare our own data types.  For our example, we’ll declare valid types of colors.  When we don’t assign our types values in our enum, we can still use numerical values that will read the index.  A value of 0 would be read as Colors.Red.

enum Colors {Red, Blue, Green};
let color: Colors;

color = 0;

However, by assigning values to our enum data types, numerical values can no longer be used and the direct call of the data type must be used.

enum Colors {Red = 'red', Blue = 'blue', Green = 'green'};
let color: Colors;

color = Colors.Red;

At the bottom of this file you can add the following line to print the color to the console.

console.log(color);

To see it in action, first go to Terminal or Command Prompt again and transpile the code.

tsc ./main.ts

After, you can type in the following, where you should see one of your colors appear as the reply.

node main.js

Terminal showing node running main.js file

Like earlier, you can find more information about enums in the documentation for TypeScript: https://www.typescriptlang.org/docs/handbook/enums.html

In the next lesson, we’ll start learning how functions work in TypeScript.

 

Transcript 1

Hi everybody, my name is Bryce Airs and I’ll be taking you through TypeScript today. So, TypeScript is a super set of JavaScript meaning that JavaScript is valid TypeScript, however TypeScript is not valid JavaScript.

So TypeScript has to be transpiled into JavaScript in order for it to be compatible and run on various browsers. But it does some very important things for us and it gives us type safety as well as gives us Intellisense, meaning, as you can kind of see here, as you start typing it automatically will bring up and try to autocomplete what it is you’re typing which can be very beneficial. Helps prevent a lot of typos and errors and such. So, let’s go ahead to get started, let’s go over to Node.js.org and here you will see two different downloads you can get. I’m on a Mac, if you’re on Windows it probably says Windows there or Linux. But go ahead and select the one that says LTS, long term support, this is going to be, not the most recent, but it’s the most stable.

So go ahead and click on that to download, that will download to your computer, then once it’s downloaded just double click to install. Then, from there, you need to install TypeScript. So after you install Node you should have NPM available, which NPM is a Node Packet Manager. So from here you could download this, but we’ll actually go to the quick start. Excuse me, not the quick start. Here you can see if you’re launching it using TypeScript with various things. On a future video tutorial I’ll be using Angular and Angular CLI specifically which will automatically transpile your TypeScript into JavaScript.

Let’s go to the documentation here, actually download. So if you click on the download link, and this is over at typescriptlang.org then click on the download link and you’ll see this NPM install. So you can take this, oops, there we go. And control c, or command c on Mac, and we come over to our terminal and you can paste that in. And that will go ahead and install TypeScript. So now if you type which tsc, if you’re on Windows it’s probably a different command, to figure out where it’s located. But great, so it shows we have it installed. So now we can run this TSC command, now we’ll go ahead and transpile our code for us, which is super handy. So next we need an editor.

So the editor I recommend is Visual Studio Code. It has great support for TypeScript, there’s a big button here, download for Mac. Probably says download for Windows, or Linux, et cetera.

So go ahead and click that, download it, and then once it’s downloaded double click to install and go through the install commands. So in the next video we’ll actually go ahead and create some files and get started.

Transcript 2

Hey, everybody, welcome back; in our last video, we got Typescript installed, node, with node npm installed, and we also installed the editor, we haven’t launched any of it yet, so let’s go ahead and create our first file, here, so we can actually open up our editor, say code dot, and if that didn’t open up for you, you can manually open up the editor, and you go up here, and you go File > Open, so here, we’ll see Open Editors, these will be files that we currently have open, which we don’t have any.

This is for searching, this is for source control, this is Debugging, and then here, we have Extensions, go ahead and type in typescript, and you’ll see one called TypeScript Hero; this is one I recommend, click the Install button, it will probably ask you to restart, you just click the button, and it will restart for you.

Perfect, so if we go back over here, we can click the New File button, or we can right click and say New File, and we’ll say main.ts for typescript, make this a little bigger, so you can see, and from here, we can start working on our project, so to get started, I’m going to type in export, and we normally don’t have to do this, this is just because we can get some weird errors, since we won’t actually be exporting or anything, we’ll just be doing all our commands in this one file.

So, the first thing we want to talk about is, normally, in javascript, when we declare a variable, we say var a equals 10, but we’re typically not going to use var if we can help it; what we want to use is let, and const, so let is just like var, except to the way it’s scoped, so let kind of helps you in some of those gotcha cases, it’ll actually scope it to the curly braces, so it’s block scoped, rather than var, is function scoped, so only when it’s in a function is it actually scoped.

So, that’s kind of one of the big problems with using var in JavaScript, is it all of a sudden gets hoisted and becomes globally scoped; const, on the other hand, you can’t re-declare it, so then, if I tried to say, c equals nine, it’s going to not like that, because, cannot assign c because it is constant, or a read only property, so that’s kind of one of the big perks, there.

Some of the other variables we have, we declare, are, we can say, number, so we don’t actually have to do an assignment, like in javascript, you actually do an assignment; here in typescript, we can actually just say this is equal to something, and it’s going to be of type, number, so later, when we got to declare, we say d equals hello, it’s not going to like that, because hello is not assignable to type number.

So it’s a really nice feature of typescript, kind of catching all those cases where we don’t want to reassign something to the wrong type, so change this back to a, here, we can also say string, and also, of the type of boolean, and then we also have the type, any, so this is very useful in cases where you have some api you’re calling, that you may or may not be getting back certain property; you may have some weird cases, you’re not sure what the type is going to be, could be a string, could be a number, could be boolean.

So, you want to use any, in that case, but if you use any, you’re not going to get some of the helpers that you normally get, or the intel sense, excuse me, static type checking that you normally get; there’s also a cool feature of strings, which I will show you now, let’s say b equals, and we use back ticks, and this is for string interpellation, and we can say ‘Hello World’ from a multiline!

We can save that, so this is perfect, and then, in here, what we can do, is we can actually transpile that code, so we can say tsc, or typescript, say target, we’ll say ECMAScript 2016, and let’s say dot slash, we’ll say main dot ts, that’s the file we want to transpile, and we could actually use the dash dash watch property, here, so that’ll just go ahead and run, and I’ll watch for any file changes, so we come back over here, we’ll see we have another file, called main js, and you’ll see it’s transpiling to ECMAScript 2016.

We could also do, so you want target 2015, and I’ll watch for changes, say this is a number, and we save, and you’ll see it’s saved here, let’s see, that doesn’t look right; we’ll just leave this off, here, I want to give it a target, there we go, because in ES2016, you can actually use let and const, so this is actually reverting back to ES5, where it’s actually using vars, which is really nice, so you can see here, it automatically is throwing in the new lines for us, so that’s some really, really, cool features that we wouldn’t normally get.

Transcript 3

So in our last video, we learned how to declare simple types, like boolean, number, NE.

Let’s go ahead and get rid of that for now. And let’s work on some more advanced types here. So we can say let string array. And you’ll make that a type. Let’s say string array. You can use capital S, lower case s. But this is declare an array of strings. So string array could equal hello world. Oop. And there again, we caught a type-o. Perfect. So you can see there, works great. We could also do call a generic array. And it’d be type array of string. So this is syntactically the same as this guy up here. Only difference, you can’t have a lowercase here. So this has to be uppercase, and the type is declared here. So then you could say generic array equals, and we could say, say hey and hello.

So these are pretty much both the same. So we come back here and run that. Oops. Then we can see our code is declared with vars. Everything’s looking good. So the next thing we’re gonna look at is a Tuple. So, a Tuple’s just like an array, essentially, in this case. But it happens to have different types. So these work great when the type is all string, or all number, or all boolean. But what if you had mix-match of types? Which would be what a Tuple could be good for. So, in this case, we could say let myTuple equal, oops, not equal, we’re declaring a type here, not setting it to a value. And we could say number boolean. Great.

And now we could say myTuple equals and if we say this, it’s gonna get an error. Hover over, ’cause it’s not assigned a type number and boolean. Okay, so let’s fix it. Say this is a three. It’s still gonna be an error, because this needs to be a boolean, which is a true or false. And we do that, and we see it resolves. Perfect. So one last type here I wanna show you is enum. And we’ll say colors. And we’ll declare some colors. We’ll say red, blue, green, whoops. And now we can say let color equal, uh, let color be of type colors. So we haven’t actually declared a variable, we’re just setting an enum.

So this type’s a little different from the Tuple since the Tuple’s basically an array. And then we can say let color, oop, say color equals colors dot red. Which would be, basically, a zero. So we say zero, it would be the same thing. So if you hover over, in the enum, if you don’t assign properties, the default is going to be setting it to its numerical place in the Tuple. But we could say red, blue, green to give them default properties. Now we see we have a problem, ’cause this is expecting a string called red. So that doesn’t even work anymore. So you’d have to go colors dot red. Now you see, now that fixes our problem.

So that works when they’re defaults, and they’re default to numbers. But once you start assigning them to values, that’s when you have some issues. So this may not be that helpful, but imagine if you had the word gray. And people misspell this all the time. They could put grey or gray. Just wanna make sure we use gray. So now if we went colors dot and we get type ahead, type gray, everything works great if we type gray with an e, that’s gonna be wrong. Perfect.

Then we go console dot log. And we can say color. And we come over here, we’ll compile it. And then we’ll say node. Main dot js. So we wanna run the js file. And we get the color gray. Perfect.

Interested in continuing? Check out the full TypeScript for Beginners course, which is part of our Full-Stack Web Development Mini-Degree.