What is TypeScript: Introduction and Easy Start Guide

What is TypeScript?

An open-source programming language, TypeScript has gained popularity in recent months. It allows JavaScript, which is software that controls the browsing of websites and apps, to be extended with new features. Many see this as a positive since it helps bolster future innovation while keeping existing code bases safe.

Created by Microsoft, this programming language overcomes some of the challenges of working with Javascript. It is built on top of Javascript and therefore all Javascript files are technically TypeScript files.

On a basic level, TypeScript allows you to set variables so that they can only be assignable to a specific data type.

You can think of plain vanilla JavaScript as the script that tells us what will happen in the play. TypeScript assigns roles (type classification) to the individual actors (variables that we create) so that they know what part they have to play. And if all goes well, our application will perform wonderfully and we may even get a standing ovation.

What is TypeScript and how it works?
What is TypeScript and how does it work?


Written by Microsoft engineers and architects David Nalidikumutadilla and Edward Z. Yang, there are numerous tutorials online for anyone wanting to learn how to use TypeScript.

Before we begin with TypeScript here are the fundamental concepts you should be familiar with following JavaScript concepts:
  • Variables
  • Arrays/Objects/Functions
  • Arrow Functions
  • Destructuring

In this article, we will go over what TypeScript is, why you might want to use it, and how to get started.

The future of JavaScript

Even though many people are using JavaScript, it’s still an immature language. It is becoming more popular but adoption is slow.

There are several reasons why JavaScript is not very popular.

First, most people that use JavaScript do so as developers or in writing plugins for their platform. They don’t have to know how to interact with the end user since they code in HTML and CSS which is what users will be doing some time after learning how to write web pages.

Second, even if you aren’t a developer, you probably need to handle some complex interactions between content (e.g google maps, modals, widgets) and your web page. You can’t just assume that everyone has browser extensions enabled since those things require permissions from the user.

Third, there are lots of websites that work well until you look closer at them. Then you find out that they are loading resources like Flash or interacting with Web APIs that are no longer supported. For example, when you click on a link and then start typing into a search box, this makes the request via Ajax instead of through HTTP GET.

Because these sites were built before the rise of cross-platform development platforms such as Electron or NwJS, there was no real incentive to optimize performance. When developing apps for mobile devices then optimizing for speed is easier than testing different browsers and supporting features such as device automation or local storage

Why you SHOULD use it

Type Script grants us some convenient benefits such as:

Static Typing: the ability to set a variable's TYPE and therefore not allow it to be assigned a value of any other type. Some examples of programming languages that use static typing are C++, C#, and Java. Plain Javascript on the other hand, along with Python and Ruby, uses Dynamic Typing, meaning that a variable can be reassigned to a variety of different types of data.
 //Static Typing (C++/C#/Java)
int number = 5; // This is fine
number = 'abc'; // this will error 

 //Dynamic Typing (JavaScript, Python, Ruby)
let number = 10; // this works
number = 'a' // this will also work 

  • TypeScript compilation allows us to find errors in our typescript at compile time as opposed to when we run our application or unit tests.
  • Shorthand notations
    • Features not available or not yet available in plain JavaScript that allow us to write cleaner, more efficient code.
  • Most code editors nowadays have support for typescript which enables us even more benefits such as:
    • Code Completion
    • Refactoring

Why you SHOULDN'T use it

Since TypeScript offers some features that JavaScript does not provide, you will need to constantly transpile your TypeScript files into JavaScript files to ensure they can be run properly. This can be especially tedious if you are just working on simple applications.

When Should you use it?

Simply put, TypeScript's benefits are more apparent when working on medium to large projects and/or with a team of developers to ensure they and you don't have any unexpected problems when running your program.

Plain vanilla JavaScript is best when you want to keep your projects simple and finish them in an efficient timeframe.

Difference between TypeScript vs Javascript

what are the differences between Typescript Vs Javascript
what are the differences between Typescript Vs Javascript


TypeScript introduction

Welcome to the wonderful world of Typescript!

This article will give you an easy start on typing javascript codes with types, also known as type-safe programming.

You’ll learn how to enable type checking when editing your code files, and what tools are available for doing it. You’ll also learn how to use several key features that help make development faster and easier.

Note that this tutorial is written for version 2 of typescript. If you’re using earlier versions, some things may work differently, can be deprecated, or missing.

Also note that while writing this article, we used typescript itself to create a simple project to demonstrate its capabilities. You can find the source code for this project here: https://github.com/jslinterceptors/ts-interceptor-demo

We will discuss why you might want to try to at end of this article.

But first, let’s see how to get started with typescript coding to develop software applications.

Where to start with TypeScript

JavaScript is mostly used as a programming language these days, but it’s not your only option for scripting languages. You may already be familiar with some of them!

That’s right, TypeScript is another option for writing flexible script-based applications. And what’s interesting about TypeScript is that you don’t have to use it. You can write scripts in any JS framework or software library you like.

Getting Started with TypeScript

In your code editor's terminal, you'll use your node package manager (or npm) to install typescript globally by running the command:
npm i -g typescript

Once the installation is complete you can verify the installation by running:
tsc -v and you should receive a response with the version number.

After verifying that you have the type script installed, you can start writing your first TypeScript program by creating a .ts file.

Inside this new file, you can write any JavaScript code and it will be valid TypeScript code.
example:
 let age: number = 28; 

The syntax is very similar to plain JavaScript but you'll notice a difference with the colon. This denotes the typing of the variable age.
If you were to try to reassign this value to something other than another number you will get an error.

Now that we have a single line of TypeScript code, we can run the command: 'tsc ' to run our compiler and transpile our .ts file into a .js file.

You should see the new .js file now and inside of it would look something like this:
 var age = 28 
As you can see, the code you wrote in TypeScript has now been translated into plain javascript. However, by default, the TypeScript compiler will set variables to var instead of let or const. If we wish to change this, we will have to make some configurations for our compiler.

Configuring the TYPESCRIPT Compiler

To do this, run 'tsc --init' in your terminal. This will create a tsconfig.json file which you can modify to fit your needs.

configuring TYPESCRIPT Compiler example
configuring TYPESCRIPT Compiler example


To use a configuration you will just have to uncomment the line you wish to configure. There are a lot of configurations in this file that you don't necessarily need to understand but the more common ones are:
  • target: You can set this to any ES version (ES2016/ES2017/ES2018...). ES2016 is a very common and most used version so that will likely work best for you in most situations.
  • rootDir: The configuration that specifies the directory that contains our src files. By default, it is set to "./" which represents the current folder.
  • outDir: This configuration specifies the directory where our transpiled.js files will be sent.
  • removeComments: If you add this configuration and keep it set to true, any comments you typed in your TypeScript code will not be transpiled in your .js files.
  • noEmitOnError: This will stop the compiler if there are any errors in our TypeScript code.

After you finish setting up your configuration, you can now run 'tsc' instead of 'tsc ' to transpile ALL .ts files in your application.

But there are benefits to using TypeScript, especially since most front-end devs now know how to code. Learn more about the advantages here >

What is a type?

When you write code, you use types to enforce good coding practices. With types, there’s more confidence that your program will correctly run.

Types can help make sure your codebase isn’t filled with bugs or flaws. They can also help ensure that new people added to the project aren’t overburdened with learning about the inner workings of the app.

For example, if you are writing some custom functions for an application, it would be helpful to add type definitions into the project so programmers don’t have to worry as they use these functions.

There are many different types you can define in Typescript, but let’s look at one in detail. To do this, we’ll need to create a new file inside our project folder. We’re going to name this file my-type.ts.

Here, you can see what type definition looks like.

Type casting

One of the most common features in any language is type conversion. Even if you’re writing PHP, which doesn’t have type conversion, you can still use it by enabling it in your scripts.

PHP allows you to perform type casting easily. When used effectively, it prevents vulnerabilities such as injection or log stuffing.

In PHP, there are two ways to do typecasting. The first one is using the ‘ (double arrow) symbol followed by the variable name. 

For example, assign numeric values to variables using that symbol. Then, at the end of the assignment statement include the extension syntax where variable = variable → cast, etc. This way we can limit the scope of our typing and make sure that our data fits into the appropriate types.

The second method requires the use of single quotes around variable names. Thus they can be converted directly from string datatypes. However, this is less safe than the previous method. It cannot protect us from issues like XSSI though.

Type casting also reduces compatibility problems when working with languages such as JSX and React since they both support similar type conversions.

Type inference

Type inference is one of the coolest features of TypeScript. It can automatically figure out what type you are trying to assign to an object or parameter. This can greatly reduce the amount of typing you have to do when programming in JavaScript.

Let’s take this example from above. We have a Person class with first name, last name, and age property. With only two properties inside the person class, we already have three types that need to be inferred by the compiler.

The infer option –strict will make the process take longer but the result will be better. In our case, it will try to determine the type for us using some rules it has built-in.

In the case of assigning someone to a variable, like a john below. The compiler will know that data should come back from the assignment knowing that john won’t be null or undefined.

This helps prevent common mistakes such as handing people code that expects certain inputs which might not exist (like passwords without any characters) or outputs which don’t match up (such as a login form that requires user input).

Building types with type declaration

A typed language is a programming language that has explicit typing. The compiler checks your code to make sure it follows certain constraints. This can prevent bugs and help avoid mistakes. Using typed languages also helps developers write better software because they use more structured tools.

There are several ways to explicitly declare types in JavaScript. Some of these, such as using normal variables or declaring classes, work for any program written in JavaScript. Other methods require special syntax, which only compiles inside a strict mode  (e.g., var answer = question() requires an object with a function named "answer", rather than just putting an alert(question())).

The easiest way to have some type checking in your programs is to use the built-in ‘typeof’ check. It will quickly become obsolete if you use another method instead. For example, typeof myVar === "number" is the same thing as doing Number(myVar)!== myVar, but easier to read.

But what if you want to use something else other than typeof? There are two main libraries for this: typescript.org and flowtype.com

Using interfaces

Writing code from an interface is one of the core concepts in programming today. Well, it’s called encapsulation, but everybody calls it writing code from an interface.

There are two ways to write code that uses an interface: literal implementation or indirect abstraction.

A literal implementation means putting actual data into variables and using concrete types. The problem with this approach is that it can be very difficult to understand what’s going on under the hood.

Indirect abstractions solve this issue by creating a layer between your application and the internal mechanics of how you work. Your job as a programmer then becomes focusing on what you want to do rather than how you want to do it.

This is why indirect abstraction via interfaces is essential. By inserting a middle step, interfaces enable other people (or software) to do some things more easily.

For example, imagine you have a shopping app and you need to calculate shipping costs. You could create a separate function for calculating them and call that from within your addToCart() function, but if you used the API instead, you would just get the cost back out as part of the returned object.

Another benefit of using an interface is loose coupling. With tight coupling, all elements of your system will know about each other and any change will likely affect multiple systems.

By implementing components through their interfaces, they become loosely coupled, making evolution and maintenance easier.

Conclusion

There you have it, you should now know what is TypeScript and be set up to start typing in TypeScript! Of course, there are many more nuances to this Typescript programming language but I hope this was a good read to get you to start learning! Stay tuned for more information!

Post a Comment

Previous Post Next Post