Typescript,

Michael Schneider
5 min readJan 18, 2020

The Short Version

by: Michael Schneider

Photo by:
drmakete lab on unSplash

Typescript is an open source programming language from Microsoft. It is a super-set of JavaScript and compiles down to plain JavaScript.

Typescript is useful for its direct relation to JavaScript. Typescript allows us to declare variable types and if not provided will infer types for us based on what the variable is initially assigned. Typescript also allows us to use features like Intellisense provided by Visual Studio Code to give us a list of prototype methods that can be used on our variable type. It will also alert us if we try to reassign a variable a different type. Lastly Typescript is becoming more and more popular and can be used with Angular, React and Vue. This article serves as a quick starter guide to get you up and running. It assumes basic knowledge of JavaScript and terminal use.

Getting Started

To begin playing around with Typescript let's go to our terminal. Install Typescript globally by using the command:

npm i -g typescript

Touch a new .ts file and add some code for a simple console.log

let greeting = 'Hello World';
console.log(greeting)

Before you run your new Typescript file you'll need to compile it down to regular JavaScript. If your file was named main.ts you would use the following terminal command to compile it:

tsc main.ts

Run the file through node.js and you'll see the output //'Hello World'

node main

You might see an error now at the top of your .ts file. This is because the scope of a JavaScript file is normally set to the global scope and we want to be scoped to this particular module. To remove the error add an empty export to the top of the file:

export {}

To have our files compile automatically for us we can put a watch flag after our compile command in the terminal:

tsc main --watch

Variable Types

Variables can be assigned three basic types: boolean, number or string:

let isClicked: boolean = false;
let totalClicks: number = 0;
let name: string = 'Steve;

Variables can also be declared with embedded expressions:

let sentence: string = `My name is ${name} and I've clicked ${totalClicks} times.`

Defining variable types allows for static type checking. We'll get an error if we try to assign a variable a different type. With types we also get to access Intellisense, which will provide methods that are related to the variable type.

Type null and undefined are subsets of all other types. So they can be assigned on their own or as a subset of boolean, string or number.

let var1: null = null;
let var2: undefined = undefined;
let var3: boolean = null;
let var4: string = undefined;

There are two ways to declare arrays:

let array1: number[] = [1,2,3];
let array2: Array<number> = [1,2,3];

A tuple is a data type which allows us to declare sets containing different types.

let person1: [string, number] = ['Johnny', 22];

If you're unsure what a value will be you can assign it the : any type. This will allow the value to be reassigned and can be helpful if you're just learning Typescript. It encompasses values of all different types and does not force us to do any checking before we try to call, construct or access properties on the variable. Note that the following code will generate no errors from Typescript, but would fail when rendered. As such, use type any with discretion, as it generally reverses the point of using Typescript in the first place.

let random: any = 10;
random = 'maybe';
random = true;
console.log(random.try)
random();
random.toUpperCase();

Type inference; even if you don't specify a type to a variable, if you assign it a value typescript will infer a type.

let b = 20

Typescript infers that b is a number. You can specify a union of types for the same variable if it needs multiple types:

let mixType: number | string;
mixType = 12;
mixType = 'twelve'

Functions

We can declare what type variable parameters will be in functions at the same time that we declare their names:

function addNums(num1: number, num2: number) {
return num1 + num2
}

From the above function Typescript will infer that the output is a number, but if you need to declare the output directly you can do so as follows:

function addNums(num1: number, num2: number): number {
return num1 + num2
}

Typescript will assume all parameters are mandatory by default. If we want to make a parameter optional, we can append a ? to the end of it. For example if we want to be able to call the above function with only num1 we can write it like this:

function addNums(num1: number, num2?: number) {
return num1 + num2
}

Optional parameters must follow the mandatory ones. We can also assign a default value to the parameter as another way of dealing with optional parameters.

function addNums(num1: number, num2: number = 12) {
return num1 + num2
}

Objects and Interfaces

We can use interfaces to define what type variables our values will be within objects. For Example:

interface Student {
name: string;
enrolled: boolean;
cohort: number;
}

Now if we need to use a student object we use Student as our type:

function printDetails(student: Student) {
console.log(`${student.name}, ${student.enrolled}, ${student.cohort}`)
}

let somebody = {
name: 'Jane',
enrolled: false,
cohort: 1608
}

printDetails(somebody);

We can also make values optional or set them to a default the same way we did in functions by using either ? or assigning it a value when declared.

Classes and Access Modifiers

We can take advantage of Typescript in classes by declaring our variables and their types before the constructor

class Robot {
serialNum: number;

constructor(Num: number) {
this.serialNum = Num;
}

welcome() {
console.log(`beep, beep, ${this.serialNum}`);
}
}

We can also use class inheritance to extend previously constructed classes and their types by passing the variable through super:

class Bender extends Robot {
constructor(serialNum: string) {
super(serialNum);
}
activate() {
console.log("Bending Girder.")
}
}

Access modifiers set the accessibility of properties and methods in a class from public, private and protected. By default all properties and methods are set to public. If we set a property to private it will not be accessible from outside its containing class. For example if we changed our Robot class to read as follows:

class Robot {
private serialNum: number;

...

then:

let newRobot = new Robot(123);
console.log(newRobot.serialNum)

we would get an error because we have set serialNum to be private. At most we could see it by invoking its welcome method.

newRobot.welcome()
// "beep, beep, 123"

Private also prevents inherited classes from being able to access the parent variables. As such, private can be a bit too extreme and we can use a slightly looser type of protected.

class Robot {
protected serialNum: number;

...

Now we could run the following code:

let bender = new Bender(555);
bender.welcome()
//"beep, beep, 555"

Without changing serialNum to protected from private, bender would not have had access to his own serial number.

Those are the basics of Typescript!

Check out more resources:

--

--

Michael Schneider

Front End Developer, Designer, Tinkerer, Map Maker…