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:
-
On line 3 of this code snippet, we declare a local variable named
testand assign ita stringvalue. We then use theconsole.logfunction to print its value to the console. We display a message indicating that the assignment of a string value totestwas successful. -
On line 12, we assign an integer value of
1to thetestvariable and print its value to the console. We display a message indicating that the assignment of an integer value totestwas successful. -
Finally, from line 24 — 26, we assign a function that takes two parameters, named
aandb, to thetestvariable and print its value to the console. We display a message indicating that the assignment of a function totestwas 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:
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:
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 theindex.tsfile.
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.
Here, we are declaring four variables using the var keyword: myString, myBoolean, myNumber, and myStringArray.
myStringis a string variable initialized with the value`Hello`.myBooleanis a boolean variable initialized with the valuetrue.myNumberis a number variable initialized with the value1234.myStringArrayis 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:
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.
In the updated code:
On line 2, we are assigning the value of the statement
myBoolean.toString()to themyStringvariable. The type of thetoStringmethod is string.On line 6, we are assigning the value of the statement
myNumber === 456to themyBooleanvariable. 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
myNumbervariable 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
myStringArrayarray to themyNumbervariable. Again, this is allowed since the length property of an array is of typenumber.
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
myStringis initially set to the string"Hello". However, it is then reassigned to the string representation of the value ofmyBoolean, which istrue. -
The value of
myBooleanis determined by comparing the value ofmyNumberto . Since the value ofmyNumberis not equal to ,myBooleanis set tofalse. -
The value of
myStringArrayis then set to an array with two elements: a string representation of the value ofmyNumber, and the string"5678". -
The value of
myNumberis set to the length ofmyStringArray, which is two.
We can see from the output of the console.log statements that these values are being set and logged as expected.