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
.
// With strictNullChecks set to true let a: null = null; // Ok let b: undefined = null; // Error let c: number = null; // Error let d: void = null; // Error // With strictNullChecks set to false let a: null = null; // Ok let b: undefined = null; // Ok let c: number = null; // Ok 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.
// With strictNullChecks set to true let a: undefined = undefined; // Ok let b: undefined = null; // Error let c: number = undefined; // Error let d: void = undefined; // Ok // With strictNullChecks set to false let a: undefined = undefined; // Ok let b: undefined = null; // Ok let c: number = undefined; // Ok 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
.
// With strictNullChecks set to true let a: void = undefined; // Ok let b: void = null; // Error let c: void = 3; // Error let d: void = "apple"; // Error // With strictNullChecks set to false let a: void = undefined; // Ok let b: void = null; // Ok let c: void = 3; // Error 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:
let a: boolean = true; let b: boolean = false; let c: boolean = 23; // Error 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.
// With strictNullChecks set to true let a: number = undefined; // Error let b: number = null; // Error let c: number = 3; let d: number = 0b111001; // Binary let e: number = 0o436; // Octal let f: number = 0xadf0d; // Hexadecimal let g: number = "cat"; // Error // With strictNullChecks set to false let a: number = undefined; // Ok let b: number = null; // Ok let c: number = 3; let d: number = 0b111001; // Binary let e: number = 0o436; // Octal let f: number = 0xadf0d; // Hexadecimal let g: number = "cat"; // Error
When the target version is set to ES6, the above code will compile to the following JavaScript:
let a = undefined; let b = null; let c = 3; let d = 0b111001; let e = 0o436; let f = 0xadf0d; 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:
var a = undefined; var b = null; var c = 3; var d = 57; var e = 286; var f = 0xadf0d; 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.
// With strictNullChecks set to true let a: string = undefined; // Error let b: string = null; // Error let c: string = ""; let d: string = "y"; let e: string = "building"; let f: string = 3; // Error let g: string = "3"; // With strictNullChecks set to false let a: string = undefined; // Ok let b: string = null; // Ok let c: string = ""; let d: string = "y"; let e: string = "building"; let f: string = 3; // Error 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:
let e: string = "building"; let f: number = 300; let sentence: string = `The ${e} in front of my office is ${f} feet tall.`;
Upon compilation, you will get the following JavaScript:
// Output in ES5 var e = "building"; var f = 300; var sentence = "The " + e + " in front of my office is " + f + " feet tall."; // Output in ES6 let e = "building"; let f = 300; 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
. 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
.
// With strictNullChecks set to false let a: number[] = [1, 12, 93, 5]; let b: string[] = ["a", "apricot", "mango"]; let c: number[] = [1, "apple", "potato"]; // Error let d: Array= [null, undefined, 10, 15]; let e: Array = ["pie", null, ""]; // With strictNullChecks set to true let a: number[] = [1, 12, 93, 5]; let b: string[] = ["a", "apricot", "mango"]; let c: number[] = [1, "apple", "potato"]; // Error let d: Array = [null, undefined, 10, 15]; // Error let e: Array = ["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:
let a: [number, string] = [11, "monday"]; let b: [number, string] = ["monday", 11]; // Error let c: [number, string] = ["a", "monkey"]; // Error let d: [number, string] = [105, "owl", 129, 45, "cat"]; let e: [number, string] = [13, "bat", "spiderman", 2]; e[13] = "elephant"; 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.
enum Animals {cat, lion, dog, cow, monkey} let c: Animals = Animals.cat; console.log(Animals[3]); // cow 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
.
enum Animals {cat = 1, lion, dog = 11, cow, monkey} let c: Animals = Animals.cat; console.log(Animals[3]); // undefined 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.
let a: any = "apple"; let b: any = 14; let c: any = false; let d: any[] = ["door", "kitchen", 13, false, null]; 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.
let a: never; // Ok let b: never = false; // Error let c: never = null; // Error let d: never = "monday"; // Error function stuck(): never { while (true) { } }
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.
Powered by WPeMatico