TypeScript Up & Running: The Basics

Mouafa Ahmed
codessert
Published in
6 min readSep 19, 2016

--

TypeScript Up & Running is an articles series, in each article we will try to dive deeper in the TypeScript syntax and features

In this first article we’ll discover the basics of TypeScript, particularly we’ll know more about types and how we can use them, but first what’s TypeScript?

Well TypeScript was created by Microsoft and as written in the website:

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

TypeScript add syntactic sugar layer on top of Javascript which is static type checking, and this layer help us spotting runtime bugs while we develop.

So actually we will continue to code with JavaScript, we can even convert our current .js files to .ts (typescript file extension), and that will not cause any problem, next we can start add types specification.

TypeScript was used in many projects like Angular 2, ionic and Aurelia, thats why we hear a lot about Typescript recently.

For this article we will use TypeScript playground, but feel free to follow this link to integrate it in your workflow.

Introduction to Types

So basically JavaScript contains 6 types, they are:

  1. String: represents sequence of characters e.g. var s = “Hope”
  2. Number: represents numeric values e.g. var n = 10;
  3. Boolean: represents boolean value either false or true
  4. Undefined: represents undefined value e.g. var x; x now contains undefined
  5. Null: represents null e.g var x = null
  6. Object: represents non-primitive data like: Function, RegEx, Array, Map, Date … etc

TypeScript supports by default those types, so now to declare a variable, we can add a type like this

var s : string = “Hope”
var n : number = 10
var x : void = null // void used for null and undefined
var isReady : boolean = false
var list: number[] = [1, 2, 3]
var wherever : any

Those examples show how we can use Typescript while declaring our variables, the any type allows the wherever variable to accept any type.

For more details about Typescript types follow this link

Now let’s start with a real world scenario, with this sample function:


function concat(a, b) {
return a + b
}
concat('hello ', 'world!') // return 'hello world!'
concat('Johnny ', '5') // return 'Johnny 5'
concat(5, 6) // return 11

Notice how the concat function change its behavior according to their argument, so if the first argument is a string it will work dine, but if we call it with two numbers its behavior will become a mathematical addition!.

we can fix this behavior by converting both arguments to strings during the concatenation like this

function concat(a, b) {
return a.toString() + b.toString()
}
concat('hello ', 'world!') // return 'hello world!'
concat(5, 6) // return 56
concat(true, false) // return 'truefalse'

sure this will fix the number addition, but what if the arguments was neither a string or number, you can see that the concat function will continue to work with booleans, what if we want the concat function to work only with strings or numbers.

well this where Typescript with its static type checking shine 🌟

function concat(a: string , b: string) {
return a.toString() + b.toString()
}
TypeScript notify us about type error

You can see how TypeScript now handle type checking and force us to use the string type. But what if we want our concat function to accept both strings and numbers, well we can.

notice that we can use the or operator for types with or without parentheses

Now Typescript accepts both string and number types, rather than that it will notify us about the wrong argument types.

The next step is to specify the return type of the concat function, in this case it will be string all the time.

function concat(a: string | number , b: string | number) : string {
return a.toString() + b.toString()
}

notice that when we specify the returning type to be number, Typescript notify us that the current returning type is string and it’s not assignable to type number

So now we are sure that the concat function will only accept string or number and for all cases it will always return a string.

Since sum must be a number it cannot accept the concat function which return a string

even if we remove the secure layer of .toString() conversion, TypeScript will notify us, about the scenario when a and b could be numbers.

TypeScript is a static type checking tool, and the reason that it force us to use the toString method is because we allow the the concat function to accept number, and we force the return type to be string, TypeScript notice that there is a probability of calling concat with both a and b holding a number, which in this case the ‘+’ sign will work as mathematical addition, and that will cause the concat function to return a number!, and thats not what we want.

Typescript on the left, Javascript on the right

Notice, the code on the right side contain no type checking or other things. it is no more than sample javascript code, and that’s what the browser will run.

Remember, TypeScript is a static type checking tool, and it only check our code in the development process, which means the run time code will not check for any type error.

More advanced arguments type checking

In this section we will dive more in the type checking and how to use function overloads, so we will extend our concat function to handle arrays concatenation

function concat(a: string | number | any[],
b: string | number | any[]): string | any[] {
if (a instanceof Array) {
return a.concat(b)
} else {
return a.toString() + b.toString()
}
}

Notice how we used any[], which means an array containing any data type, if we want to accept only array of string we use string[], same for number number[].

The problem in this code is that we can pass a as an array and b as string or number, what if we want both a and b to be from the same type, and here where function overloads came handy.

function concat(a: string, b: string) : string {}
function concat(a: number, b: number) : string {}
function concat(a: any[], b: any[]) : any[] {}
function concat(a: string | number | any[], b: string | number | any[]) : string | any[] {
if (a instanceof Array) {
return a.concat(b)
} else {
return a.toString() + b.toString()
}
}

Notice how added three declaration of the concat function, each one represent a specific way of calling the concat, now Typescript will allow us to call the concat function with the declare rules, arguments a and b must be from the same type.

Now what if in another dimension we want to support all arguments that contains the toString() method, well we can.

function concat(a: {toString}, b: {toString}) : string | any[] {
return a.toString() + b.toString()
}

now concat will accept any arguments if they have toString method, but please use this with caution, because this is too general.

Enough For Now, In subsequent parts of this article, We’ll learn more about interfaces, classes and generics.

If you liked this, click the 💚 below so other people benefit

My Twitter: @mouafa

--

--

Mouafa Ahmed
codessert

Lead FrontEnd Developer, JavaScript Evangelist, UX Consultant, Instructor & Speaker