Search⌘ K
AI Features

Strong Typing and Basic Types

Learn to understand and apply strong typing in TypeScript, differentiating it from JavaScript's dynamic typing. Explore basic types like string, number, boolean, and arrays, and see how TypeScript enforces type safety through type annotations.

We'll cover the following...

JavaScript is not strongly typed. It is a language that is very dynamic, as it allows objects to change their types, properties, and behavior on the fly. TypeScript, however, is strongly typed and, as such, will enforce rules that govern how we use variables, functions, and objects.

We will start with the concepts of strong typing or static typing, as it is also known. We will then move on to exploring some of the basic types that the language uses and how the language can detect what type a variable is based on how and where it is used within our code. We will then tackle the basics of function signatures and finally see how to import and use third-party JavaScript libraries.

Strong typing

Strong typing means that when we create a variable or define a parameter in a function, we specify what type it is. Once this type has been specified, we cannot change it. Loose typing is the exact opposite of this concept, and JavaScript is a loosely typed language.

As an example of loose typing in JavaScript, let’s take a look at the following code:

Javascript (babel-node)
// Declare a variable called "test" and initialize it with a string value
console.log("Let's declare the variable 'test' with a string value\n");
var test = "a string";
// Log the value of "test" to the console
console.log("test = " + test);
console.log("\nWe can see the successful assignment of a string type to the 'test' variable.\n");
// Change the value of "test" to an integer
console.log("Now let's assign an integer value to 'test'\n");
test = 1;
console.log("test = " + test);
console.log("\nWe can see the successful assignment of an integer type to the 'test' variable. Notice that the type of the 'test' variable has changed from a string to an integer.\n");
// Change the value of "test" to a function
console.log("Now let's assign a function to 'test'\n");
test = function (a, b) {
return a + b;
}
console.log("test = " + test + "\n");
console.log("This is how types work in JavaScript: variables can hold values of any data type, and the type of a variable can change during the execution of a program. This is in contrast to strongly-typed languages like TypeScript, in which variables must be explicitly declared with a specific data type and can only hold values of that type.");
Loose typing in JavaScript
  • On line 3 of this code snippet, we declare a local variable named test and assign it a string value. We then use the console.log function to print its value to the console. We display a message indicating that the assignment of a string value to test was successful.

  • On line 12, we assign an integer value of 1 to the test variable and print its value to the console. We display a message indicating that the assignment of an integer value to test was successful.

  • Finally, from line 24 — 26, we assign a function that takes two parameters, named a and b, to the test variable and print its value to the console. We display a message indicating that the assignment of a function to test was successful.

When we click on the “Run” button, we can clearly see the changes that we are making to the test variable. It changes from a string value to a numeric value and then finally becomes a function.

Unfortunately, changing the type of a variable at runtime can be a very dangerous thing to do. If our code is expecting a variable to be a number and tries to perform calculations on it, the results of these calculations may be unexpected if the variable held a string.

In a similar way, if a variable is a function that does something, and someone inadvertently changes that variable into a string, a whole block of functionality has suddenly become lost.

TypeScript is a strongly typed language. This means that if we declare a variable to be of type string, then we need to treat it as a string throughout our code base.

So, how do we declare that a variable should be of a particular type? Well, TypeScript introduces a simple notation using the colon ( : ) symbol to indicate what type a variable should be, as follows:

TypeScript 4.9.5
// Declare a variable with the type "string"
var myString: string;
// Assign a value to the "myString" variable
myString = `This is a string`;
// Log the value of "myString" to the console
console.log("myString = " + myString);
Assigning string value to variable

Here, we can see that we have declared a variable named myString, and have followed it with a colon and the string keyword before we assign a value. This technique is called type annotation, and it sets the type of the myString variable to be of type string.

If we were to now try and assign a number to it, TypeScript would generate a compilation error as follows:

Files
index.ts
tsconfig.json
TypeScript 4.9.5
// Declare a variable with the type "string"
var myString: string;
// Attempt to assign a value of type "number" to the "myString" variable
myString = 1;
// This assignment will result in an error, because "myString" has been explicitly declared as a string type
// and can only hold values of the string type
Incorrect value assignment for string type

Here, we have a TS2322 error, which indicates that the type ‘1’ (which is of type number) is not assignable to a variable that has been specified as being of type string.

Note: The output of the compiler will let us know which line is generating this error, as well as where in the line the error is occurring. In this case, the error message index.ts(5,1) means that the error occurred on line 5, column 1 of the index.ts file.

Take a look at the code and see if you can come up with a solution to resolve the error.

Basic typing

TypeScript provides a number of basic types that can be used for type annotation. As an example of these types, let’s focus on four common types, namely string, number, boolean, and array. Let’s take a look at the following example to see them in action.

TypeScript 4.9.5
// Declare a string variable named 'myString' and initialize it with the value "Hello"
var myString: string = `Hello`;
// Declare a boolean variable named 'myBoolean' and initialize it with the value true
var myBoolean: boolean = true;
// Declare a number variable named 'myNumber' and initialize it with the value 1234
var myNumber: number = 1234;
// Declare an array of strings named 'myStringArray' and initialize it with the values ["first", "second", "third"]
var myStringArray: string[] = [`first`, `second`, `third`];
Variable declaration with type and value

Here, we are declaring four variables using the var keyword: myString, myBoolean, myNumber, and myStringArray.

  • myString is a string variable initialized with the value `Hello`.

  • myBoolean is a boolean variable initialized with the value true.

  • myNumber is a number variable initialized with the value 1234.

  • myStringArray is an array of strings initialized with the values [`first`, `second`, `third`].

The type of each variable is specified using TypeScript’s type annotations, which are added after the variable name and a colon (:). For example, the myString variable is annotated with the string type, which indicates that it can only hold string values. The myStringArray variable is annotated with the string[] type, which indicates that it is an array of strings.

All of the highlighted statements in the below code widget are now invalid:

TypeScript 4.9.5
// Declare a string variable
var myString: string = `Hello`;
// Declare a boolean variable
var myBoolean: boolean = true;
// Declare a number variable
var myNumber: number = 1234;
// Declare an array of strings
var myStringArray: string[] = [`first`, `second`, `third`];
// Assign the value of 'myBoolean' to 'myString'
myString = myBoolean;
// Assign the value of 'myNumber' to 'myBoolean'
myBoolean = myNumber;
// Assign the value of the first element in 'myStringArray' to 'myNumber'
myNumber = myStringArray;
// Assign the value of 'myString' to 'myStringArray'
myStringArray = myString;
Mismatched value type assignments

This output is clearly telling us that we are not allowed to assign values from one type to another.

Let’s fix this code now.

TypeScript 4.9.5
// This line sets the value of the `myString` variable to the string representation of the value of the `myBoolean` variable.
myString = myBoolean.toString()
// This line sets the value of the `myBoolean` variable to a boolean value that represents
// whether the value of the `myNumber` variable is equal to 456.
myBoolean = myNumber === 456;
// This line sets the value of the `myStringArray` variable to an array with two elements:
// 1. The string representation of the value of the `myNumber` variable.
// 2. The string '5678'.
myStringArray = [myNumber.toString(), `5678`];
// This line sets the value of the `myNumber` variable to the length of the `myStringArray` array.
myNumber = myStringArray.length;
// These lines log the current values of the `myString`, `myBoolean`, `myStringArray`, and `myNumber` variables
// to the console.
console.log(`myString = ${myString}`);
console.log(`myBoolean = ${myBoolean}`);
console.log(`myStringArray = ${myStringArray}`);
console.log(`myNumber = ${myNumber}`);
Type conversion and assignment updates

In the updated code:

  • On line 2, we are assigning the value of the statement myBoolean.toString() to the myString variable. The type of the toString method is string.

  • On line 6, we are assigning the value of the statement myNumber === 456 to the myBoolean variable. The type of the equals expression is boolean, as it will result in either true or false. So, in this case, the right-hand side of the assignment is of the same type as the left-hand side of the assignment and is, therefore, valid TypeScript.

  • On line 11, we are then converting the myNumber variable into a string using the .toString() function and creating an array out of it, with the value `5678` by enclosing both in two square brackets "[" and "]".

  • On line 14, we are assigning the length property of the myStringArray array to the myNumber variable. Again, this is allowed since the length property of an array is of type number.

In this code, we can see that the values of the variables myString, myBoolean, myStringArray, and myNumber are being set and logged to the console:

  • The value of myString is initially set to the string "Hello". However, it is then reassigned to the string representation of the value of myBoolean, which is true.

  • The value of myBoolean is determined by comparing the value of myNumber to 456456. Since the value of myNumber is not equal to 456456, myBoolean is set to false.

  • The value of myStringArray is then set to an array with two elements: a string representation of the value of myNumber, and the string "5678".

  • The value of myNumber is set to the length of myStringArray, which is two.

We can see from the output of the console.log statements that these values are being set and logged as expected.