Advertisement
  1. Code
  2. Coding Fundamentals

TypeScript for Beginners, Part 2: Basic Data Types

Scroll to top
This post is part of a series called TypeScript for Beginners.
TypeScript for Beginners, Part 1: Getting Started
TypeScript for Beginners, Part 3: Interfaces

After reading the introductory TypeScript tutorial, you should now be able to write your own TypeScript code in an IDE that supports it and then compile it to JavaScript. In this tutorial, you will learn about different kinds of data types available in TypeScript.

JavaScript has seven different data types: Null, Undefined, Boolean, Number, String, Symbol (introduced in ES6), and Object. TypeScript defines a few more types, and all of them will be covered in detail in this tutorial.

The Null Data Type

Just as in JavaScript, the null data type in TypeScript can have only one valid value: null. A null variable cannot contain other data types like number and string. Setting a variable to null will erase its content if it had any.

Remember that when the strictNullChecks flag is set to true in tsconfig.json, only the value null is assignable to variables with null type. This flag is turned off by default, which means that you can also assign the null value to variables with other types like number or void.

1
// With strictNullChecks set to true

2
let a: null = null; // Ok

3
let b: undefined = null; // Error

4
let c: number = null; // Error

5
let d: void = null; // Error

6
7
// With strictNullChecks set to false

8
let a: null = null; // Ok

9
let b: undefined = null; // Ok

10
let c: number = null; // Ok

11
let d: void = null; // Ok

The Undefined Data Type

Any variable whose value you have not specified is set to undefined. However, you can also explicitly set the type of a variable to undefined, as in the following example.

Keep in mind that a variable with type set to undefined can only have undefined as its value. If the strictNullChecks option is set to false, you will also be able to assign undefined to variables with number and string types, etc.

1
// With strictNullChecks set to true

2
let a: undefined = undefined; // Ok

3
let b: undefined = null; // Error

4
let c: number = undefined; // Error

5
let d: void = undefined; // Ok

6
7
// With strictNullChecks set to false

8
let a: undefined = undefined; // Ok

9
let b: undefined = null; // Ok

10
let c: number = undefined; // Ok

11
let d: void = undefined; // Ok

The Void Data Type

The void data type is used to signify the lack of a type for a variable. Setting variables to have a void type may not be very useful, but you can set the return type of functions that don't return anything to void. When used with variables, the type void can only have two valid values: null and undefined.

1
// With strictNullChecks set to true

2
let a: void = undefined; // Ok

3
let b: void = null; // Error

4
let c: void = 3; // Error

5
let d: void = "apple"; // Error

6
7
// With strictNullChecks set to false

8
let a: void = undefined; // Ok

9
let b: void = null; // Ok

10
let c: void = 3; // Error

11
let d: void = "apple";  // Error

The Boolean Data Type

Unlike the number and string data types, boolean only has two valid values. You can only set its value to either true or false. These values are used a lot in control structures where one piece of code is executed if a condition is true and another piece of code is executed if a condition is false.

Here is a very basic example of declaring Boolean variables:

1
let a: boolean = true;
2
let b: boolean = false;
3
let c: boolean = 23; // Error

4
let d: boolean = "blue"; // Error

The Number Data Type

The number data type is used to represent both integers and floating-point values in JavaScript as well as TypeScript. However, you should remember that all numbers are internally represented as floating-point values. Numbers can also be specified as Hexadecimal, Octal or Binary literals. Keep in mind that Octal and Binary representations were introduced in ES6, and this can result in different JavaScript code output based on the version you are targeting.

There are also three additional special symbolic values that fall under the number type: +Infinity, -Infinity, and NaN. Here are a few examples of using the number type.

1
// With strictNullChecks set to true
2
let a: number = undefined; // Error
3
let b: number = null; // Error
4
let c: number = 3;
5
let d: number = 0b111001; // Binary
6
let e: number = 0o436; // Octal
7
let f: number = 0xadf0d; // Hexadecimal
8
let g: number = "cat"; // Error
9
10
// With strictNullChecks set to false
11
let a: number = undefined; // Ok
12
let b: number = null; // Ok
13
let c: number = 3;
14
let d: number = 0b111001; // Binary
15
let e: number = 0o436; // Octal
16
let f: number = 0xadf0d; // Hexadecimal
17
let g: number = "cat"; // Error

When the target version is set to ES6, the above code will compile to the following JavaScript:

1
let a = undefined;
2
let b = null;
3
let c = 3;
4
let d = 0b111001;
5
let e = 0o436;
6
let f = 0xadf0d;
7
let g = "cat";

You should note that the JavaScript variables are still declared using let, which was introduced in ES6. You also don't see any error messages related to the type of different variables because the JavaScript code has no knowledge of the types we used in the TypeScript code.

If the target version is set to ES5, the TypeScript code we wrote earlier will compile to following JavaScript:

1
var a = undefined;
2
var b = null;
3
var c = 3;
4
var d = 57;
5
var e = 286;
6
var f = 0xadf0d;
7
var g = "cat";

As you can see, this time all the occurrences of the let keyword have been changed to var. Also note that the octal and binary numbers have been changed to their decimal forms.

The String Data Type

The string data type is used to store textual information. Both JavaScript and TypeScript use double quotes (") as well as single quotes (') to surround your textual information as a string. A string can contain zero or more characters enclosed within quotes.

1
// With strictNullChecks set to true

2
let a: string = undefined; // Error

3
let b: string = null; // Error

4
let c: string = "";
5
let d: string = "y";
6
let e: string = "building";
7
let f: string = 3; // Error

8
let g: string = "3";
9
10
// With strictNullChecks set to false

11
let a: string = undefined; // Ok

12
let b: string = null; // Ok

13
let c: string = "";
14
let d: string = "y";
15
let e: string = "building";
16
let f: string = 3; // Error

17
let g: string = "3";

TypeScript also supports template strings or template literals. These template literals allow you to embed expressions in a string. Template literals are enclosed by the back-tick character (`) instead of double quotes and single quotes that enclose regular strings. They were introduced in ES6. This means that you will get different JavaScript output based on the version that you are targeting. Here is an example of using template literals in TypeScript:

1
let e: string = "building";
2
let f: number = 300;
3
4
let sentence: string = `The ${e} in front of my office is ${f} feet tall.`;

Upon compilation, you will get the following JavaScript:

1
//  Output in ES5

2
var e = "building";
3
var f = 300;
4
var sentence = "The " + e + " in front of my office is " + f + " feet tall.";
5
6
//  Output in ES6

7
let e = "building";
8
let f = 300;
9
let sentence = `The ${e} in front of my office is ${f} feet tall.`;

As you can see, the template literal was changed to a regular string in ES5. This example shows how TypeScript makes it possible for you to use all the latest JavaScript features without worrying about compatibility.

The Array and Tuple Data Types

You can define array types in two different ways in JavaScript. In the first method, you specify the type of array elements followed by [] which denotes an array of that type. Another method is to use the generic array type Array<elemType>. The following example shows how to create arrays with both these methods. Specifying null or undefined as one of the elements will produce errors when the strictNullChecks flag is true.

1
// With strictNullChecks set to false

2
let a: number[] = [1, 12, 93, 5];
3
let b: string[] = ["a", "apricot", "mango"];
4
let c: number[] = [1, "apple", "potato"]; // Error

5
6
let d: Array<number> = [null, undefined, 10, 15];
7
let e: Array<string> = ["pie", null, ""];
8
9
10
// With strictNullChecks set to true

11
let a: number[] = [1, 12, 93, 5];
12
let b: string[] = ["a", "apricot", "mango"];
13
let c: number[] = [1, "apple", "potato"]; // Error

14
15
let d: Array<number> = [null, undefined, 10, 15]; // Error

16
let e: Array<string> = ["pie", null, ""]; // Error

The tuple data type allows you to create an array where the type of a fixed number of elements is known in advance. The type of the rest of the elements can only be one of the types that you have already specified for the tuple. Here is an example that will make it clearer:

1
let a: [number, string] = [11, "monday"];
2
let b: [number, string] = ["monday", 11]; // Error

3
let c: [number, string] = ["a", "monkey"]; // Error

4
let d: [number, string] = [105, "owl", 129, 45, "cat"];
5
let e: [number, string] = [13, "bat", "spiderman", 2];
6
7
e[13] = "elephant";
8
e[15] = false; // Error

For all the tuples in our example, we have set the type of the first element to a number and the type of the second element to a string. Since we have only specified a type for the first two elements, the rest of them can be either a string or a number. Creating tuples b and c results in an error because we tried to use a string as a value for the first element when we had mentioned that the first element would be a number.

Similarly, we can't set the value of a tuple element to false after specifying that it will only contain strings and numbers. That's why the last line results in an error.

The Enum Data Type

The enum data type is present in many programming languages like C and Java. It has been missing from JavaScript, but TypeScript allows you to create and work with enums. If you don't know what enums are, they allow you to create a collection of related values using memorable names.

1
enum Animals {cat, lion, dog, cow, monkey}
2
let c: Animals = Animals.cat;
3
4
console.log(Animals[3]); // cow

5
console.log(Animals.monkey); // 4

By default, the numbering of enums starts at 0, but you can also set a different value for the first or any other members manually. This will change the value of all the members following them by increasing their value by 1. You can also set all the values manually in an enum.

1
enum Animals {cat = 1, lion, dog = 11, cow, monkey}
2
let c: Animals = Animals.cat;
3
4
console.log(Animals[3]); // undefined
5
console.log(Animals.monkey); // 13

Unlike the previous example, the value of Animals[3] is undefined this time. This is because the value 3 would have been assigned to dog, but we explicitly set its value to 11. The value for cow stays at 12 and not 3 because the value is supposed to be one greater than the value of the last member.

The Any and Never Types

Let's say you are writing a program where the value of a variable is determined by the users or the code written in a third-party library. In this case, you won't be able to set the type of that variable correctly. The variable could be of any type like a string, number, or boolean. This problem can be solved by using the any type. This is also useful when you are creating arrays with elements of mixed types.

1
let a: any = "apple";
2
let b: any = 14;
3
let c: any = false;
4
let d: any[] = ["door", "kitchen", 13, false, null];
5
6
b = "people";

In the above code, we were able to assign a number to b and then change its value to a string without getting any error because the type any can accept all types of values.

The never type is used to represent values that are never supposed to occur. For example, you can assign never as the return type of a function that never returns. This can happen when a function always throws an error or when it is stuck in an infinite loop.

1
let a: never; // Ok

2
let b: never = false; // Error

3
let c: never = null; // Error

4
let d: never = "monday"; // Error

5
6
function stuck(): never {
7
    while (true) {
8
    }
9
}

The Union Type

When you are writing a program, there will always be times when you will have to use variables that could be of multiple types. For example, a variable to store the width of UI elements could be a number or a string. Similarly, you could use a variable to keep track of the padding applied around an element. In such situations, defining a variable to be a single type will not cut it, and using the any type will just make it accept all kinds of variables without throwing errors.

You can overcome these shortcomings with the help of the union type. As the name suggests, it's basically a union of two or more types.

1
let elemWidth: number|string = 10; // Ok

2
elemWidth = "50%"; // Ok

3
elemWidth = [12, 30]; // Error

4
5
let elemPadding: number|number[] = 20; // Ok

6
elemPadding = [5, 10, 5, 20]; // Ok

7
elemPadding = [5, "10", 15, 20]; // Error

All data types have a specific set of methods that you can call. For example, you can use the includes() method to check if a string contains another substring in JavaScript. However, this method does not make sense when called on numbers.

Defining a variable using a union type automatically limits your access to methods that are only available to all the included data types. Calling the includes() method on the elemWidth variable above would result in errors for this reason. Here is a screenshot for VS Code that shows the error message when we call includes() on elemWidth.

TypeScript Union Data TypeTypeScript Union Data TypeTypeScript Union Data Type

Using Data Types in Function Definitions

Functions handle a lot of our programming logic. These functions also usually accept some variables as input in the form of parameters and then return a result with either the same or a different type of data. TypeScript allows us to specify the data type of each parameter as well as the type of data we expect the function to return. This can be very helpful when you are working on large projects with a lot of functions that accept multiple parameters.

You can specify the data type for different function parameters after the name of each parameter. The return type of the function goes after the parameter list. Here is an example:

1
function clampNumber(n: number): number {
2
    return Math.max(0, Math.min(n, 255));
3
}
4
5
function rgbToHex(r: number, g: number, b: number): string {
6
 
7
    let cr = clampNumber(r);
8
    let cg = clampNumber(g);
9
    let cb = clampNumber(b);
10
11
    let color = "#" + cr.toString(16).padStart(2, '0') + cg.toString(16).padStart(2, '0') + cb.toString(16).padStart(2, '0');
12
    return color;
13
}
14
15
let black: string = rgbToHex(0, 0, "0");
16
let red: number = rgbToHex(255, 0, 0);
17
let blue: string = rgbToHex(0, 0, 255);

We have defined two functions here. The clampNumber() function takes an input number and clamps its value between 0 and 255. The rgbToHex() function then takes three different numbers and converts them to hexadecimal format after clamping and returns a string.

We call rgbToHex() three times in our code above. However, the first two calls result in an error because of incorrect parameter type and incorrect return type respectively. The code won't transpile into JavaScript until we resolve those errors. This type checking for function parameters and return values helps us write error-free code, which ultimately improves productivity.

Final Thoughts

This tutorial introduced you to all the types that are available in TypeScript. We learned how assigning a different type of value to a variable will show errors in TypeScript. This checking can help you avoid a lot of errors when writing large programs. We also learned how to target different versions of JavaScript.

If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato marketplace.

In the next tutorial, you will learn about interfaces in TypeScript. If you have any questions related to this tutorial, let me know in the comments.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.