When you work with types in TypeScript, you are actually working with JavaScript itself. All the basic data types of JavaScript are also still there: Boolean, number, string, null, and undefined. They hold the same kinds of values and work in the same way. Plus, in TypeScript, you can explicitly define exact values for variables, functions, and other parts of your code, with literal types. This functionality makes sure that the value not only matches the correct data type (such as a number or a string) but must also be a specific value within that type. Let's jump in and explore both primitive data types and the use of literal types.
Boolean
Boolean is the data type that can contain only one of two possible values: true or false. In TypeScript, we can use either let or const to assign a Boolean value to a variable, like we do in JavaScript.
let start = false; // start is false
start = true; // start is now true
const finish = true; // finish is true
// finish = false; // This will cause an error because you can't reassign a const variable
As you can see, you can change the Boolean value for the variable start. But if you try to change the finish variable, which is declared with const, you'll get an error because const means it can't be changed once set. When it comes to changing the data type of those variables, TypeScript is even stricter. You can't usually change these variables to other types of data in TypeScript because it makes sure the types match. If you really need to make this change, you could use the any or unknown types, but think of them as a last resort.
In TypeScript, if you want to explicitly define the Boolean type for a variable, you can declare it by adding a type annotation. When you declare a variable with a type annotation, you can change its value later, but the new value must still match the type specified in the annotation.
let isTrue: boolean = true; // This is okay
console.log(isTrue); // Outputs: true
isTrue = false; // Also okay
console.log(isTrue); // Outputs: false
For example, when you declare a variable with the Boolean type in TypeScript, like isTrue in the example above, you're saying that this variable can hold either a true or false value. You can later change the value of isTrue to false if you like and without any issues because false is also a Boolean value.
Literal types
So, what happens when you want to be even more precise and you narrow down a variable to one specific value? This is where literal types in TypeScript come into play. Literal types let you define not only the exact type but also the exact value for your variable. To specify a literal type for a variable, we use a colon after the variable name.
let alwaysTrue: true = true; // This is okay
console.log(alwaysTrue); // Outputs: true
alwaysTrue = false; // This will give a TypeScript error
Here, the variable alwaysTrue has been declared as only being able to hold the literal value true. Therefore, it can only ever be true, and it is not possible to assign false or any other value to alwaysTrue. If you try to do so, TypeScript will throw an error.
Logical operators
Last but not least, in TypeScript, we can use logical operators like AND &&, OR ||, and NOT ! to work with Boolean values. We can also use the equality operators === and ==, with === checking both value and type, and == checking only the value.
To see how the comparison work, let's declare two variables a and b, and assign true to one and false to the other:
let a: boolean = true;
let b: boolean = false;
- When we use AND
&&operator to compare them, it will returnfalsebecause the&&operator returns true if both operands aretrue:
console.log(a && b); // Outputs: false
- On the other hand, the
||operator returnstruewhen comparing these variables, as||givestrueif at least one operand istrue:
console.log(a || b); // Outputs: true
- And, the NOT
!operator changes the Boolean value of a variable to its opposite. So in our case,awill be reassigned withfalse, andbwill betrue.
console.log(!a); // Outputs: false
console.log(!b); // Outputs: true
Before we move on, let's take a look at how the equality operators work:
let num: number = 5;
let str: string = '5';
console.log(num === str); // Outputs: false
console.log(num == str); // Outputs: true
In TypeScript, there are two ways to check if values are equal: using === or ==.
- The
===operator checks if the values are the same and if they are of the same type. So,5 === '5'would be false because one is a number and the other is a string. - The
==operator is less strict and only checks if the values are the same, not their type. So5 == '5'would be true because it automatically changes the string to a number before comparing.
Number
In TypeScript, the type number can include all kinds of numbers: It can be negative and positive integers (whole numbers), 0, floating-point numbers (as we know as decimals) like 0.5 and -2.419435.
let age: number = 25;
const pi: number = 3.14;
console.log(age); // Outputs: 25
console.log(pi); // Outputs: 3.14
In the code example above, you see the variables age and pi declared with let and const. Other than this conventional type declaration methods, TypeScript also allows you to explicitly define the variable type or constrain its numeric value.
When we look at the following code lines, we see the type of num1 is specified with number, and num2 is assigned a literal type of 2023. However, in the last line, when you try to reassign num3 with a value other than the literal type 1024, you will get an error. This error occurs because the value 12 doesn't match the literal type 1024.
let num1: number = 500; // number
let num2: 2023 = 2023; // 2023
let num3: 1024 = 12; // This wil give an errorString
To store textual information, we use the string data type. TypeScript supports single quotes, double quotes, and template literals to represent string types. Let's see how all this works:
let name = "The Doctor";
Here, we see a conventional type declaration with let assigning the string value "The Doctor" to the variable name.
let origin: string = "Gallifrey";
The variable origin is specified as a string type with type annotation and set to value 'Gallifrey'.
let age: '2000' = '2000';
For age, the type is a string literal '2000'. Notice that although '2000' represents a number, its type is not a number, nor is it a number literal type because it is enclosed with single quotes.
let introduction: string = `Hello, I'm ${name} from ${origin}. I'm approximately ${age} earth years old.`;
console.log(introduction);
// Outputs: Hello, I'm The Doctor from Gallifrey. I'm approximately 2000 earth years old.
Finally, the introduction is declared as a string and it uses template literals, marked by backticks `` to combine the values of other variables. The variables inside the ${} placeholders are replaced with their values when printed to the console.
Null and undefined
In TypeScript (as well as in JavaScript), null and undefined are both special values and types.
undefinedmeans that a variable has been declared, but a value hasn't been assigned to it yet.-
nullmeans that the value is intentionally left blank or empty.
However, in TypeScript, the behavior of a variable that hasn't been assigned a value depends on the compiler's configuration. In non-strict mode, the type may be inferred as any, meaning it can be assigned any value later. To explicitly define a variable as undefined or null, you would need to assign it as such or use a type annotation.
let myVariable; // the type is 'any', value is undefined
myVariable = 5; // OK, since the type is 'any'
myVariable = undefined; // OK, since the type is 'any'
In non-strict mode, as shown in the code above, myVariable is automatically assigned the type any, and its value initially set as undefined. Therefore, its value can be reassigned later, even to the value undefined again. However, in strict mode, all steps of the code above will result in a compile error.
So depending on your need, you can assign variables explicitly with either undefined or null in the following ways:
let input1 = undefined; // Changeable, no explicit type
let input2: undefined = undefined; // Using type literal 'undefined'
let item1 = null; // Changeable, no explicit type
let item2: null = null; // Using type literal 'null'Conclusion
In this topic,
- you explored basic TypeScript data types like Boolean, number, string, null, and undefined;
- you learned how to create variables using conventional declaration methods, which we also use in JavaScript, and how to use literal types;
- you also looked at special cases of null and undefined.
The points covered in this topic will be a foundation for working with other data types in TypeScript and help you write clearer and more reliable code.