TypeScript 101

Gamze Yılan
Jun 23 · 8 min read

Aimed for those who are familiar with programming languages, this article is meant to teach you TypeScript quickly.

TypeScript is a Superset of JavaScript

What is TypeScript?

TypeScript is a programming language that is the superset of JavaScript. Hence, the existing programs written in JavsScript will also work for the TypeScript syntax. It’s mostly used for developing JavaScript applications, and web applications alongside other tools such as Google’s Angular framework or Node.js.

Unlike the programming languages used nowadays, JavaScript is more dynamic. For example, JavaScript is a scripting language and therefore doesn’t support structures such as objects and classes as C++ or Python does. Furthermore, JavaScript doesn’t support Static typing or modules, features that most of the latest programming languages support. It’s because of these problems with JavaScript that TypeScript is developed. And although it’s still written in JavaScript, TypeScript is object oriented and supports Static typing and modularity.

How to Set Up

In order to install TypeScript, you’ll firt need to install the NodeJS, a JavaScript running environment. Then, go to yout CLI and type in the following command;

npm install -g typescript

With this command alone on Windows, you’ve got your typescript downloaded. If you are on Mac, though, remember to put sudo before npm.

To chech whether the TypeScript is downloaded properly and see the version you’ve downloaded, use the command below;

tsc — version

Your First TypeScript Code

In order to start writing your first TypeScript code, you need to create a file named main.ts. The ts extension stands for TypeScript file. You can create this file either via CLI or simply using the desktop. Then, go to your preferred IDE and open the file. We’ve named the file “main” because as with any programming language, the main file will run first and the project will simply not run if there isn’t one.

Now you can type in any JavaScript or Typescript code within this file. After done, save the project. In order to run the project, you need to first translate the code into JavaScript because if you’ve written it in TypeScript the browser won’t be able to read it and even if you’ve written it in JavaScript, the file extension is .ts so it won’t run without the translation. To translate, go to your terminal and do;

tsc main.ts

Where tsc stands for TypeScript compiler. After that, either go to the folder or use the CLI to list what’s inside the directory and you’ll see that alongside main.ts you also have a main.js file. If you look inside, you’ll see that the code within has been translated to JavaScript.

Now although you can manually translate the TypeScript code using tsc, most tools and frameworks will do this automatically. Angular, for example, will perform this translation within runtime. When you use the ng serve command within your project, as the Angular structure serves your project through your computer via localhost port, the CLI will automatically call the TypeScript Compiler.

Notice: All JavaScript code is a valid TypeScript code, however, any TypeScript code needs to be translated into JavaScript in order to work as.

To run either of the files, simply go under the folder that contains the files and use the;

node main.ts/main.js

TypeScript Basics

  • Variable Declarations

You can use both var and let tags to declare a variable, in both JavaScript and TypeScript.

var number1=1;

let number2=2;

The difference between let and var is seen when working within a function. Let’s study the code below;

function doSomething (){

for (var i=0; i<5; i++) {

console.log(i);}

console.log(‘Finally: ‘+i);}

doSomething();

With the usage of var, the i value will be searched for within the nearest function hence this code will work. However, with the usage of let instead, the i value will be searched for within the nearest scope. Hence, the the code above won’t work.

The old method of declaring a variable, var, is not healthy as for we’d like to use the scope logic when working with a complex program.

Notice: Even when you have a compilation error, the TypeScript Compiler will still create a .js version of the compiled .ts file.

  • Variable Types

Let’s say that we’ve created a variable, assigned a data of one type and then changed the value to a data of another type as shown below;

let name=’Alice’;

name=5;

The structure above will work well on JavaScript as it allows you to change the variable’s type on the fly. However, this can cause many issues when working with complex programs. That’s why, with TypeScript, this is not allowed and hence the code above won’t work.

If you want a variable that you can change the data type of within the program, you can still do it with TypeScript. All you need to do is to not assign a value to it when declaring and after that, the type will change based on what value you assing to it, once or many times within the program.

If you don’t want to assign a value to a variable yet still have it be of a certain data type when using TypeScript, use the syntax below;

let a :number;

let b :string;

There are 6 different variable types that you can use within TypeScript: number, string, boolean, any (for all types of data), array and enum. Below, you can find the syntax to all.

let a:number;

let b:string;

let c:boolean;

let d:any;

let e: number []= [1,2,3]; //For an array of numbers. Type any data type you’d like instead of number.

let f: any[]=[1, ‘Alice’, 34, ‘Hello’, true];

enum Color {Red=0, Yellow=1, Purple=2}; //Used for naming numbers a certain name

  • Type Assertions

In some cases, we might need to specifically tell the TypeScript compiler the type of a certain variable. Let’s study the code below;

let message; //Creates a variable with the type ANY

message=’abc’;//Assigns a string to the variable, but the type is still ANY

let funct1=message.endsWith(‘c’);// endsWith is a function that is supposed to check if a string ends with the letter typed within, in this case ‘c’

let funct2=(<string>message).endsWith(‘c’); //Type Assertion made

let funct3=(message as string).endsWith(‘c’);//Type Assertion made

In the example above, the func1 won’t work because the endsWith method works with strings only. Even though we’ve assigned a string value to the message variable, it’s type is still ANY. So in such cases, we need to tell the compiler the type of the variable specifically and we do that with type assertion, as shown above.

  • Arrow Functions

Let’s say that we’re trying to create a function of one line and give a name to it. In JavaScript, we’d do it like this;

let x=function(message) {

console.log(message);}

However, TypeScript allows something called an Arrow Function to make things easier. With Arrow Function, you can simply write the same method above as this;

let x=(message)=>console.log(message);

Where instead of declaring that there’s a function by typing function and adding curly brackets, we simply used an arrow.

  • Interfaces

Let’s say that we’re writig a function called driveCar. There are many attributes to a car: the gas level, the motor situation, the pedal power etc. Now you can create all these as variables to use within the function, but typing all these attributes one by one as parameters would not only look bad and be hard to do but also make your code hard to read. So instead of that, we simply create an object that holds all the parameters and declare the attributes of the said object below as;

let driveCar=(attributeObject)=>{//… }

driveCar ({

speed: 100;

gas: 200;

pedalPower: 50; })

However, the structure above won’t work because we haven’t declared exactly what attributes the object will hold and what the data types of said attributes are. Since an object is derived from a class, we need something that’s at least resembling a class, right? So here we use the interfaces. Which are basically blueprints, or simplified classes. Their purpose is to make sure that two ends of a puzzle actually fit together. An interface could be;

interface bluePrint{

speed:number;

gas:number;

pedalPower:number; }

And keep in mind that since every object must have the class name as the data type, we write our original function not as shown above but like this;

let driveCar=(attributeObject : bluePrint)=>{//… }

  • Classes

In object oriented programming we have something called cohesion: in short, it’s the idea that relating things should be all a part of a single unit. Now the interface method that we’ve used above is mostly usable, but if you’re building a function that’ll drive a car chances are you are going to need much more like a function that gets the data of gas, or to calculate the speed. All these relating functions and attributes are going to make your code hard to read and edit. So instead, we use classes.

The idea of building a class and deriving objects from a class is exactly same in TypeScript as in any other object oriented programmin language.

Notice: When writing a class structure, make sure to use this keyword each time you use a variable within the class in a function within the same class. This keyword will make sure that the program uses the value of the variable determined for each object derived from the class, and not confuse it with the values of the same variable within other objects of the said class.

Tip: When running the same command for multiple files through the CLI, you can simply use double ampersands as shown in the structure below;

command file1name && file2name

Tip: When creating a new object from a class using TypeScript, make sure to use the following structure.

let objName = new className();

Tip: You can, instead of typing in a value for each attribute for the said object one by one, create a constructor within the original class that takes the attribues as parameters and declare their values within the creation of each object. See the structure below;

class {//…

constructor (x:number, y:number){

this.x=x;

this.y=y; //… }

let objName = new className(100, 200);

However, if you do this you won’t be able to create an object without any parameters since for the class to work the constructor must work and for the constructor to work there must be parameters. So in order to fix this issue, we can make the parameters optional by using the question marks as shown below;

class {//…

constructor (x?:number, y?:number){

this.x=x;

this.y=y; //… }

let objName = new className(100, 200);

Notice: When you use the question mark for a parameter to make it optional, any other parameter that is to the right of that parameter must also be optional.

Tip: If you’d like to make the parameters so that they are only declared once, and cannot be changed later during the life cycle of the object, simply go to the class structure and change the first declaration of each parameter’s tag to private. Access modifiers such as public, private and protected tags can be used within TypeScript as in the structure below:

private x: number;

y:number; //This one is not specified by the access modifiers and therefore will be assumed as public.

You can also declare the attributes for the first time within the constructor and still assign Access Modifiers to them as a prefix, as shown below;

constructor (private x?:number, private y?:number){ }

If you use this type of initializing where you assign Access Modifiers within a function, the modifiers will create a scope within the function (even if the modifiers are set as public) and work only within the function and therefore, you won’t have to use the this keyword.

  • Modules

Each file within typescript is called a module. To be able to use a function or a structure within a module in another module, you need to simply place the export keyword as a prefix.

export class exampleClass{ //… }

After that, go to the module that wants to get access to the exported function, and import the material for later use at the beginning of the file as;

import {exampleClass} from ‘./exampleModule’;

Remember that you only put the name of the module that you import from within the code, not the file type extension as well.

If there are multiple things you’d like to import, separate them using a comma;

import {exampleClass1, exampleClass2, exampleFunction1} from ‘./exampleModule’;

If you’d like to import a library instead, use;

import {exampleClass} from ‘@libraryPath’;

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Gamze Yılan

Written by

I write about all that I’m interested in: Tech, Software, Physics, Math, Art, Sports, Books and Journalism.

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.