How to Install and Begin Using TypeScript
Tags: javascript, typescript, webdev, learning
Published: 2020-01-14 01:50:48

<!-- wp:paragraph -->
<p>TypeScript is one of the current hot topics in web development and for good reasons.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>It allows us to type cast when declaring variables which means we explicitly set the type of data we expect back, throws errors if the returned data is not the type we expected to get back or if a function call has too few or too many arguments, and that's just a sampling of everything it offers.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If you'd like an overview of the data types you will find it helpful to read my <a href="https://jonathansexton.me/blog/learn-typescript-data-types-from-zero-to-hero/">previous article</a>. Reading that article isn't required but it will give you a great understanding of the data types and syntax for TypeScript.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><em>Before we start, it's important to note that TypeScript can be used in conjunction with a framework/library (TypeScript is the default in Angular projects and I have an article in the works about getting started with it) but it can also be used independent of a framework/library.</em></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><em>Also, this article assumes you have a basic understanding of JavaScript programming.</em></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>So, now we're ready to get  started with TypeScript and start making use of it's awesome features.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's dig in!</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Installing TypeScript</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>There are two main ways to install TypeScript.  The first is through <a href="https://visualstudio.microsoft.com/vs/">Visual Studio</a> (not to be confused with <a href="https://code.visualstudio.com/?wt.mc_id=DX_841432">Visual Studio Code</a>) which is an <a href="https://en.wikipedia.org/wiki/Integrated_development_environment">IDE</a>.  The 2015, 2017, and I believe 2019 versions come with TypeScript installed already.  </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This is not the route I'll be covering today since I mainly use Visual Studio Code for all of my needs.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The second way, and the way we'll focus on, is through <a href="https://www.npmjs.com/get-npm">NPM</a> (Node Package Manager).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If you don't already have NPM and/or <a href="https://nodejs.org/en/">Node</a> installed (you get NPM when you install Node), now is a great time to do so as it's a requirement for the next steps and by association a requirement to use TypeScript.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":962,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://jonathansexton.me/blog/wp-content/uploads/2019/12/image-1-1024x550.png" alt="the node js download page" class="wp-image-962"/><figcaption> The Node download page - it's a good idea to use the LTS version as it's the most stable <br></figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Once you have Node and NPM installed, open your terminal in VS Code and run the following command:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center"><code>npm install -g typescript</code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Once it's finished installing, you'll see that 1 package has been added and you'll see a message stating the version of TypeScript that was installed.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This is everything you need to start compiling TypeScript to JavaScript.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now you're ready to start writing TypeScript!</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Starting A TypeScript Project</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Let's create a TypeScript project so we can take advantage of all those great features that come along with using TypeScript.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In your editor of choice (I'm using VS Code) let's create an HTML file to be the visual side of our code.  Here's what my basic HTML file looks like:</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":977,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://jonathansexton.me/blog/wp-content/uploads/2019/12/image-2-1024x376.png" alt="html text on a dark background" class="wp-image-977"/><figcaption>Basic HTML boilerplate with some placeholder text</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Honestly, we're just using this HTML so we can have something to look at on the page.  What we're really concerned with is using the console.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You'll notice I have <code>app.js</code> linked in the head of our <code>index.html</code> file.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You're probably saying to yourself <em>I thought this was an article about TypeScript?</em> </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Well hold your horses, it is. I just want to highlight some of the differences between JavaScript and TypeScript (You'll learn where this file comes from down below).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Below you'll see a simple variable declaration and a console log statement:</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":983,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://jonathansexton.me/blog/wp-content/uploads/2019/12/image-4.png" alt="javascript code showing a username variable declaration" class="wp-image-983"/><figcaption>A simple variable declaration and console log statement</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>As a side note, if you want to disable some <a href="https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint">ES-Lint</a> rules you can place the rules at the top in comments like I've done above.  Or if you want to <strong>completely</strong> disable ES-Lint for that file only you can place <code>/* eslint-disable */</code> at the top of the file.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>And here is the browser console:</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":984,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://jonathansexton.me/blog/wp-content/uploads/2019/12/image-5.png" alt="the console inside of the firefox browser" class="wp-image-984"/><figcaption>Our userName variable inside FireFox</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Let's pretend that I'm building an application and for the <code>userName</code> I expect to always get a string back.  Along the way, I may make a mistake or my data may get mutated from another source.  </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now, <code>userName</code> is a number :(</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":986,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://jonathansexton.me/blog/wp-content/uploads/2019/12/image-6.png" alt="javascript code showing a username variable declaration" class="wp-image-986"/><figcaption>Now userName is a number!</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>And here is the browser console showing the changes to <code>userName</code> that we likely didn't want to happen if this were a production application:</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":987,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://jonathansexton.me/blog/wp-content/uploads/2019/12/image-7.png" alt="" class="wp-image-987"/><figcaption>The FireFox console showing the results of the variable mutation</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p> What if the returned <code>userName</code> was then passed into another function or used as a piece of a larger data puzzle? </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This would not only be a mess to figure out where the mutation occurred  (especially if we had a larger application) , but also would create an untold amount of bugs in our code.  </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now, let's try that same experiment in TypeScript.  To do that, we'll need to create a new file with the<code> .ts</code> extension to denote a TypeScript file.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I'll name mine <code>app.ts</code> to stay consistent with naming conventions and put the same code from our JavaScript file into our new TypeScript file.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":994,"width":600,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img src="https://jonathansexton.me/blog/wp-content/uploads/2019/12/image-8.png" alt="typescript code on a dark background " class="wp-image-994" width="600"/><figcaption>The same code from our JavaScript copied over into the TypeScript file</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>You'll notice that I'm using type casting when declaring my variable now and I'm explicitly telling TypeScript that this variable should point to a string value only.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You'll also notice that I have an error line under <code>userName</code> when I'm reassigning it's value.  </p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Compiling TypeScript With the CLI</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>To see what this looks like in our console we have to compile it to JavaScript and we do that by running <code>tsc app.ts</code> in our VS Code console (you can also run the same command in any terminal as long as you're in the correct directory).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> When we run this command it will compile our TypeScript into JavaScript  and generate another file with the same name only with a <code>.js</code> extension. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This is where that <code>app.js</code> file came from that I mentioned earlier in the article.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> To compile multiple files at once, just provide those names in your command, one after the other: <code>tsc app.ts header.component.ts</code> </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>It's possible to compile multiple TypeScript files into a single JavaScript file by adding the <code>--out</code> flag:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center"><code>tsc *.ts --out index.js</code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>There’s also a watch command which will recompile all of the TypeScript automatically anytime a change is detected, keeping you from having to manually run the compile command over and over:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center"><code>tsc *.ts --out app.js --watch</code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here's the output from that <code>tsc app.ts</code> command above:</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":996,"width":600,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img src="https://jonathansexton.me/blog/wp-content/uploads/2019/12/image-9-1024x408.png" alt="" class="wp-image-996" width="600"/><figcaption>The error in my console</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>This error tells us that there's a problem with the reassignment of <code>userName</code>.  Because we  explicitly set our variable to be a string (<em>even if I hadn't set the variable to a string the error would still occur because TypeScript infers data types</em>) we cannot reassign it to a number.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This is a great feature because it forces us to be explicit with our variable declarations and saves us from making mistakes that could prove annoying and time consuming.  If you expect a particular type of data you should get that data, otherwise you should get an error.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Using Explicitly Declarative Arrays and Objects</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Let's say I'm building a project and instead of manually setting the navigation links, I want to store that info in an array of objects.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I'll expect a specific format for the information that's stored so it's consistent across all of the links.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here's how I can set a "complex" array in TypeScript:</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":1012,"width":600,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img src="https://jonathansexton.me/blog/wp-content/uploads/2020/01/image-1-1024x51.png" alt="" class="wp-image-1012" width="600"/><figcaption>An array with a specific format</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>On the left side we declare the name of the variable <code>navLinks</code>, followed by a colon.  At the curly braces is where we start declaring the format of the information we expect in this array.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We're telling TypeScript that we expect this array to contain an object or objects with these property names and types. We expect a <code>name</code> which is a string, a <code>link</code> which is a string, and an <code>alt</code> which is also a string.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>As with other <a href="https://jonathansexton.me/blog/learn-typescript-data-types-from-zero-to-hero/">data types</a> if we deviate from the format we established for this variable, we run into errors.  </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here we tried to add a new entry that was blank and we got the following error:</p>
<!-- /wp:paragraph -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p><code>Type '{}' is missing the following properties from type '{ name: string; link: string; alt: string; }' : name, link, <sub>alt ts(2739)</sub></code></p></blockquote>
<!-- /wp:quote -->

<!-- wp:image {"id":1015,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://jonathansexton.me/blog/wp-content/uploads/2020/01/image-3-1024x97.png" alt="" class="wp-image-1015"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>We get similar errors if we try to add another entry with the wrong type of information:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center"><code>{ name: 'Jonathan', link: 15, alt: false }</code>  ❌ </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center"> <code>{ name: ['Jon','Marley'], link: `https://link123.net`, alt: null }</code>  ❌  </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center"><code>this.navLinks[0].img = '../../assets/img'</code> ❌   </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center"><code>this.navLinks[0].name = 'Barnaby'</code>✔️</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You get the idea though.  Once we establish the format, TypeScript will hold us to that format and inform us if/when we deviate from it with an error.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Also, here's a few ways to define an array:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center"><code>const arr1: Array&lt;any> = ['Dave', 35, true];</code><em> // will allow us to have any number of elements with any type</em></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center"><code>const people: [string,string,string] = ['John', 'Sammy', 'Stephanie'];</code> <em>// will throw an error if more than 3 string or any non string elements appear in the array </em></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center"><code>const people: Array&lt;string> = ['Jimmy', 'Theresa', 'Stanley'];</code> <em>//will allow us to have any number of  only string elements in our array</em></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Objects work much the same way as arrays do in TypeScript.  They can be explicitly defined with set types or you can let TypeScript do all the inferring.  Here's a basic example of an object:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center"> <code>const person: {name:string, address: string, age: number} = {name: 'Willy', address: '123 Sunshine Ln', age: 35} </code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Again, on the left side we're declaring person as the variable name with the first set of curly braces defining the format we want our data to be in.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>It is important to note that in objects, the order we define our properties in does not have to match the order of the format:</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":1031,"width":600,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img src="https://jonathansexton.me/blog/wp-content/uploads/2020/01/image-5.png" alt="" class="wp-image-1031" width="600"/><figcaption>The properties do not have to match the order in which they were defined</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:heading -->
<h2>Functions, Parameters &amp; Arguments</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Some of the greatest benefits you'll see in TypeScript come when using functions.  </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Have you ever built a function to do a specific task only to find out it's not working as you intended? </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>While using TypeScript it won't be because you didn't get/send the correct type of data or use the correct number of parameters/arguments.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here's a great example:</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":1005,"width":585,"height":259,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img src="https://jonathansexton.me/blog/wp-content/uploads/2020/01/image-1024x454.png" alt="" class="wp-image-1005" width="585" height="259"/><figcaption>A TypeScript function that should return a number</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>In our function we expect to receive 3 arguments when <code>calculator</code> executes.  However, if we receive the wrong number of arguments (too few or too many) TypeScript will give us a nice error:</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":1029,"width":600,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img src="https://jonathansexton.me/blog/wp-content/uploads/2020/01/image-4.png" alt="" class="wp-image-1029" width="600"/><figcaption>The error we get when calling a function with the incorrect amount/type of arguments</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Likewise, if we receive the wrong type of data when executing this function TypeScript will generate an error and the function will not run.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center"> <code>calculator('12', '11', 'add) ; </code>❌  </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now you may be saying to yourself <em>'So what?  That's all well and good but it doesn't seem like that's a huge deal </em>but imagine you're application is dozens and dozens of files with many layers of abstractions.  </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>A great example of this would be an Angular application with services, data models, multilevel components, and all the dependencies that go along with that.  It becomes increasingly difficult to pinpoint where an error is coming from when your application gets to be large.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>That's All</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Hopefully you can see the benefits of TypeScript now.  There are plenty more than I have outlined here and I encourage you to read the documentation if you want to find more.</p>
<!-- /wp:paragraph -->

This article was originally posted on my <a href="https://jonathansexton.me/blog">blog</a>.  Swing by and check it out :)

<!-- wp:paragraph -->
<p>While you’re there don’t forget to sign up for my <strong>Newsletter</strong>  –  you can do that at the top right of the main blog page.  I promise I’ll never spam your inbox and your information will not be shared with anyone/site.  I like to occasionally send out interesting resources I find, articles about web development, and a list of my newest posts.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If you haven’t yet, you can also connect with me on social media!  All of my links are also at the top of that page or in in my profile here on DEV.  I love connecting with others and meeting new people so don’t afraid to say hi 🙂</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Have an awesome day friend and happy coding!</p>
<!-- /wp:paragraph -->