Illustration of words about programming languages Getty Images

TypeScript Tutorial: It’s All About the Types

In this TypeScript tutorial, we delve into the language’s various data types, demonstrate how they work and provide code examples.

Over the past six years, TypeScript, an open source programming language developed and maintained by Microsoft, has gained a lot of attention and appreciation. The first version which was publicly released in 2012 has matured into a powerful front-end programming language, a favorite of developers. In fact, today’s hottest JavaScript framework, Angular, was built using TypeScript.

TypeScript inherits the capabilities and power of the ever-evolving JavaScript. But whereas JavaScript doesn’t care about types, TypeScript extends JavaScript, overlaying a type system and making JavaScript code more maintainable and easier to use. It supports previous, present and future features of JavaScript. It enables developers to write simple and clean code that leverages features of ECMAScript 3 or higher and promotes the use of industry standards and best coding practices. If you want to build powerful, scalable and maintainable web or hybrid applications that run on any browser, any host or any OS, TypeScript is the way to go.

This TypeScript tutorial is the first in a series of articles aimed at teaching you how to use TypeScript. The idea is to help you master the core concepts and get you on your way to using it in the real world.

Basic Types

The concept of types refers to data classifications, such as number, boolean, string, symbol or a custom data type like class or interface; this construct is common in object-oriented languages such as C#, C++ and Java. Types enhance code quality and understandability by providing greater context within the code. It’s much easier for the compiler to catch errors during the writing process when the types are specified.

TypeScript provides an optional (and very rich) type system for JavaScript. Types exist in JavaScript, but during coding you don’t control how types are used. With JavaScript, a browser will automatically determine the type based upon the value that is assigned to the variable. Let’s try and understand this concept with a very basic example of JavaScript code.

var product = "iPhone";

console.log(typeof (product));   // This code will output “string

product = 100;

console.log(typeof (product));   // This code will output “number

In the above example, when we assign the value “iPhone,” the browser automatically determines the data type for variable product to be string. And on the next line when we assign a number to the same variable, the type becomes a number. If you would like to test this code, open your browser and copy and paste the above code into the Console window and press the Enter button to see result.

In TypeScript, on the other hand, you specify the variable’s type; the compiler won’t let you assign a number to a string variable. See the example below.

let product: string = "iPhone";

console.log(typeof (product));   // This code will output “string

product = 100;        // This code will emit an error at compilation

Using TypeScript with JavaScript provides you the power of a dynamic language while also mitigating the kinds of mistakes that are easy to make in such a language since it exposes errors at compile time, when they’re easier to fix, rather than at runtime. This is especially important when you’re working on a bigger project with, say, 50 or 60 developers on a team. In such a scenario, you might not be able to hire all top UI developers. There will be other developers (server-side, API, etc.), and they will all write their own code. With TypeScript, you don’t have to worry about what every member of a team is doing because any errors will surface at compile time. This is a great and very practical feature.

Let’s explore each of TypeScript’s types in detail.

Boolean

A boolean data type holds a value of true or false. You can declare a boolean variable in TypeScript as shown below.

let isProductAvailable: boolean = true;

Number

Unlike various object-oriented programming languages such as Java, C# or C++, which provide different data types like int, float and decimal to hold a numeric value, TypeScript provides only one numeric data type, called number. A variable of the number data type can hold any numeric literal viz floating values, hexadecimal values, and binary as well as octal values. Below is an example demonstrating numeric variables holding different values.

let productPrice: number = 1500;

let productHexId: number = 0xf00d;

let productBinaryId: number = 0b1010;

let productOctalId: number = 0o744;

String

This data type is used to hold textual information. Like JavaScript, in TypeScript, you can use single or double quotes to assign textual content to a string variable. Below is an example of defining a variable with a string type.

let product: string = "iPhone";

We can go a little further and see how the new ECMAScript 6 syntax, used within TypeScript, is cool. Assuming that you have set a value to the product variable, you can concatenate it with other string variable by using back ticks and the ${} sign, which is an ECMAScript 6 feature. For example:

let message: string = `I love ${product}`;

console.log(message);          // This will output "I love iPhone".

Array

An array data type serves as a container to hold any number of values of the same data type. In TypeScript there are two ways to create an array: one with the [] sign and another one with the built-in generic array class. Developers with experience in object-oriented languages like C# or Java may find the second syntax more familiar and comfortable.

Here’s an example using the typical [] sign:

let products: string[] = ["iPhone 7", "iPhone 8", "iPhone X"];

And here’s an example using the built-in array class:

let products: Array = ["iPhone 7", "iPhone 8", "iPhone X"];

Tuple

TypeScript has a type, called tuple, that is useful in handling an array with elements of mixed data types (for example: [1, 4, ‘hello’, 38]). If you were to explicitly specify an array of numbers, like in the above example, that code would produce a compile time error. But by using a tuple, which is very similar to a concept used in object-oriented languages, you can create a list of strings and numbers or, for that matter, any types. Below is how we would create a tuple in TypeScript.

let productInfo: [string, number] = ["iPhone X", 7500];

A tuple is intelligent enough to understand which type is declared at which position/place in the array. From the above example, you can get a substring from the string value like this: console.log(productInfo[0].substr(0, 2));

But console.log(productInfo[1].substr(3);0, 2)); will give you an error (as shown in the picture below) . The tuple would detect that you’re using a number and the number type doesn't have a substring method.

It’s pretty cool that you don’t have to do any testing here. At compile time, you'll get a type check instead of having to wait until runtime to see that there’s an error.

Please note that you cannot assign a value of a type that is not specified in the tuple’s declaration. For example, productInfo[1] = true will give you a compile time error, since the second type you have declared is a number.

TypeScript requires that you conform to a format. This is exactly why you want type checking at compile time rather than at runtime: to ensure conforming formatting. Otherwise, if you write JavaScript inside of TypeScript, TypeScript would be able to execute that code but you would lose the ability to perform type checking at compile time.

Enum

We all love enums, and they work in TypeScript as they do with object-oriented programming languages like C#. You can manually insert values, but letting it start from 0 provides for consistency for other developers on your team.

enum ProductCategories { MobilePhones = 1, Laptops, Desktops, Tablets, OtherAccessories };

Here is an example, to get the value of the above enum.

let category: ProductCategories = ProductCategories.MobilePhones;

// This will output 1

If you wish to get the string value of an enum, you can do this by writing the following code.

let categoryName: string = ProductCategories[4]; // This will output “Tablets”

Please note that the number 4 represents the actual enum value. In the above case, number 4 represents the enum “Tablets” as it holds that value.

Any

Up to this point, we have specified types. But there can be some scenarios where you fetch data from a third-party API and you are completely unaware of the type of data returned from that API. In such cases the any data type can be very useful.

let products: any = _apiService.GetProducts();  

// The GetProducts() function is going to return some type of data from the API.

The below example shows creating a variable of the any data type and assigning it any value.

let product: any = "iPhone";

product = 200;

product = false;

product.HasValue();

In this case, the dynamic power of TypeScript becomes apparent. TypeScript has no problem with the code, because TypeScript allows you to set any value to a variable just like JavaScript does. Notice that there are no red squiggly lines anywhere, which means that there are no compilation errors. Using the any data type means there’s a higher likelihood of errors at runtime, but that’s the trade-off for not having to declare a type.

Void

The void data type is typically used as a return type while declaring functions. However, if you wish to assign the void data type to a variable, it will be able to hold only two values: undefined or null.

Here’s an example of a function with return type of void.

function setProductName(name: string): void {

  1. name = name;

}

And here’s an example of a variable declared as void.

let someItem: void;        // Declaring a variable of type void.

someItem = undefined;      // Setting undefined show no compilation error

someItem = null;           // Setting null show no compilation error

someItem = "";                 // Setting a string value gives compilation error

Note: It is always recommended to use the void data type only while declaring a function.

Undefined and Null

Like with JavaScript, TypeScript has undefined and null, which can also be used as a type while declaring a variable. But declaring a variable of type undefined or null is of no use and is meaningless. If you create a variable of type undefined, it typically means nothing, and you won’t be able to use that variable for any other purpose.

let undefItem: undefined;

let nullItem: null;

Instead, you should use these types as a value to a variable. In JavaScript, null is an assignment value and is of type object. It can be assigned to a variable as a representation of no value. Undefined, on the other hand, means a variable has been declared but has not yet been assigned a value. According to TypeScript’s guidelines, while setting a default value to an object, if you wish to choose between undefined or null, always choose undefined.

Type Inference

Type inference is the process of inferring or setting the data type to a variable based upon the value assigned during declaration. If a variable is not assigned a type during its declaration, the TypeScript compiler will automatically infer the type based upon the value assigned. Below is a simple example of type inference.

let myProduct = "iPhone";

// Please note that we have not declared a data type for variable myProduct

myProduct = 100;

// This will give an error as TS has already inferred its type as string.

Here’s what the above code looks like in a code editor.

We hope you liked this TypeScript tutorial. In upcoming articles, you will learn about some very interesting and advanced features of ECMAScript 6 and TypeScript.

Chander Dhall is chairman of the Developer Platform track at IT/Dev Connections, which takes place in Dallas Oct. 15-18.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish