Live classes
Remote live programs with full guidance and support.
JavaScript Development Bootcamp (CSN)Self-study
Study at your own pace. Fully online to fit your busy schedule.
Web Development BootcampCourses
Training courses for your organisation.
Training coursesConnect
Meet our graduates and build your future talent pool.
Meet our studentsLive classes
Remote live programs with full guidance and support.
JavaScript Development Bootcamp (CSN)Self-study
Study at your own pace. Fully online to fit your busy schedule.
Web Development BootcampCourses
Training courses for your organisation.
Training coursesConnect
Meet our graduates and build your future talent pool.
Meet our studentsDiego Zito
Code Coach at Technigo
TypeScript is like a supercharged version of JavaScript. It's pretty cool because it adds some extra features on top of what JavaScript already has.
You know, JavaScript is already pretty powerful with all its functionalities and structures, but TypeScript takes it up a notch.
The most fascinating aspect of TypeScript is its incorporation of static typing. To elaborate further, static typing involves assigning specific data categories, known as types, to variables.
TypeScript helps us understand and work with these types better.
It's like giving JavaScript a little upgrade, you know?
Let’s try to understand what TypeScript is using an analogy: imagine TypeScript as a piano teacher who's always there to guide you while you play the piano.
You know, when you're playing without any assistance, it's like using plain JavaScript, where you're free to hit any note you want, even if it's wrong. With TypeScript, it's like having a vigilant piano teacher standing beside you. As soon as you hit a wrong note, they gently scold you and help you correct it.
TypeScript, in a similar way, checks your code for any errors or mistakes. It ensures that you're playing the right "notes" by providing static typing, which helps catch potential bugs and ensures a smoother coding experience.
So, just like a piano teacher guides you towards playing flawlessly, TypeScript guides you towards writing more reliable and error-free code. It's like having a helpful mentor who wants you to become the best pianist (or programmer) you can be!
Before we dive deeper into TypeScript, let's make sure we're on the same page about types.
Ready? Let's go!
In programming languages, types refer to the different kinds or categories of information that a program can store. Information or data can be classified into various types based on its content. Programming languages often have built-in data types. In JavaScript, there are six basic data types that can be divided into three main categories:
The primitive data types in JavaScript are String, Number, and Boolean. These types can hold only one value at a time.
The non-primitive or composite data types in JavaScript are Objects, Arrays, and Functions. These types can hold collections of values and more complex entities.
Lastly, there are two special data types in JavaScript: Undefined and Null.
To summarise, primitive data types hold single values, while non-primitive or composite data types can hold collections of values and more complex entities. These are the basic data types in JavaScript.
Now, let's quickly examine each of these data types.
The string data type is employed for the representation of textual data, specifically sequences of characters. Strings are formed by enclosing one or more characters within single or double quotes, as demonstrated below:
let a = "let’s learn some TypeScript!";
The number data type is utilised to express both positive and negative numbers, with or without a decimal point:
let a = 25;
The number data type also encompasses certain unique values:
Infinity represents the mathematical concept of infinity (∞), which is greater than any number. -Infinity is the result of dividing a non-zero number by 0. NaN, on the other hand, signifies a specific value called "Not-a-Number." It arises from an invalid or undefined mathematical operation, such as attempting to calculate the square root of -1 or dividing 0 by 0, among others.
The Boolean data type is capable of holding just two values: true or false.
It is commonly employed to store values such as yes (true) or no (false), on (true) or off (false), and other similar cases, as exemplified below:
let doYouWantToLearnTypescrypt = true;
The undefined data type is limited to having only one value, which is the unique value called "undefined." When a variable has been declared but has not yet been assigned a value, it automatically takes on the value of undefined.
let undefinedVar;
console.log(undefinedVar); // Output: undefined
The value null is a special keyword that represents the absence of any object value. It is used to indicate the intentional absence of an object or the absence of a value for a variable.
When a variable is assigned a null value, it means that the variable doesn't currently hold any meaningful value or reference to an object. It is essentially an empty or void state.
let emptyVar = null;
The object data type is a versatile structure used for storing collections of data. It consists of properties, which are defined as key-value pairs.
The key (or name) of a property within an object is always represented as a string, while the corresponding value can be of any data type, such as strings, numbers, booleans, or even complex data types like arrays, functions, and other objects.
let bandName = {
name: "ABBA",
country: "Sweden",
members: 4,
genre: ["disco", 'pop', 'new wave']
};
An array is a data structure that allows you to store multiple values of the same type in a single variable. You can think of an array as a collection of related items, arranged in a specific order.
Each item in an array is called an element, and each element has a unique position within the array, which is called an index. The index represents the location of an element within the array, and it starts from 0 for the first element.
let musicEnjoyment = ["I", "love", "to", "jam", "to", "Kendrick Lamar",];
console.log(musicEnjoyment[5]); // Output: Kendrick Lamar
A function is an object that can be invoked to execute a specific block of code. To use a function, you must first declare it, specifying the code that it should execute. Later, you can simply call the function whenever you want that code to be executed.
Functions are treated as objects, which means they can be assigned to variables, as demonstrated in the example below:
let outkast = function () {
return "So fresh, So Clean!";
};
console.log(outkast()); // Output: So Fresh, So Clean!
Now that we have a clear understanding of what types are, we can delve into their functionality in JavaScript and explore the necessity of something like TypeScript.
The key aspect is that JavaScript is a dynamically typed language with loose typing. This implies that variables in JavaScript are not explicitly tied to a specific data type.
Instead, they can be assigned and reassigned values of different types.
To illustrate this concept, consider the following example:
let myVariable = 10; // myVariable is now a number
myVariable = "I love coding"; // myVariable is now a string
myVariable = true; // myVariable is now a boolean
It is evident that the content and type of the variable can be easily modified without encountering any issues.
This design choice was deliberate during the inception of JavaScript, as it aimed to be a scripting language that could be used by both programmers and designers to enhance website functionality.
However, over the years, JavaScript has grown exponentially and is now employed not only for simple website functionality but also for developing large-scale applications. In such cases, the presence of dynamic typing can give rise to trivial bugs within the codebase.
Let's illustrate this through a simple example. Suppose we have a function that takes three parameters and returns a string:
const infoAboutArtist = (artist, genre, activeYears) =>
`${artist} is a cool musical artist that makes music under the genre: ${genre}.
${artist} has been making music for about ${activeYears} years.
In 5 years this artist will be active for ${activeYears + 5} years.`;
If we invoke the function in the following manner, we obtain the expected output:
console.log(infoAboutArtist("Kendrick Lamar", "Hip Hop", 40))
//Output -
//Kendrick Lamar is a cool musical artist that makes music under the genre: Hip Hop.
//Kendrick Lamar has been making music for about 40 years.
// In 5 years this artist will be active for 45 years.
However, if by mistake, we pass the function a string as the third parameter, the output obtained will be incorrect:
console.log(infoAboutArtist("Kendrick Lamar", "Hip Hop", "40"))
//Output -
//Kendrick Lamar is a cool musical artist that makes music under the genre: Hip Hop.
//Kendrick Lamar has been making music for about 40 years.
// In 5 years this artist will be active for 405 years .
JavaScript does not generate an error in such cases because the program lacks the capability to determine the expected data type for the function. It simply accepts the parameters provided and executes the programmed actions, regardless of the data type.
As a developer, it is relatively easy to make such mistakes, particularly when working with extensive codebases or when unfamiliar with the specific parameters required by functions or APIs. This is precisely where TypeScript comes into play.
TypeScript addresses these challenges by introducing static typing, which enables the specification of data types for variables, function parameters, and return values. By doing so, it provides a layer of safety and helps catch potential errors during development, making it easier to identify and resolve issues before the code is executed.
TypeScript was introduced in 2012 and has since been developed and maintained by Microsoft.
In TypeScript, similar to other programming languages like Java or C#, it is necessary to explicitly declare the data type when creating a data structure.
By specifying the data type, the program gains the ability to evaluate whether the assigned values correspond to the declared data types.
If there is a match, the program executes without any issues. However, if there is a mismatch between the assigned values and the declared data types, an error is generated.
These errors are highly valuable as they enable developers to identify and address bugs at an earlier stage of development.
Let's revisit the previous example, but this time using TypeScript.
In TypeScript, the function would be written as follows (note that it remains the same, except for the addition of data type declarations for each parameter):
const infoAboutArtist = (artist: string, genre: string, activeYears: number) =>
`${artist} is a cool musical artist that makes music under the genre: ${genre}.
${artist} has been making music for about ${activeYears} years.
In 5 years this artist will be active for ${activeYears + 5} years.`;
Now, if I attempt to invoke the function with an incorrect data type for the parameter, I receive the following error output:
console.log(infoAboutArtist("Kendrick Lamar", "Hip Hop", "40"))
// Output -
// Error: TSError: - Unable to compile TypeScript: Argument of type 'string' is not assignable to parameter of type 'number'.
The beauty of TypeScript lies in its ability to maintain the ease of writing code similar to JavaScript while incorporating type declarations.
This is why TypeScript is often referred to as a superset of JavaScript since it introduces additional features without compromising the familiarity and simplicity of JavaScript syntax.
Let's examine the syntax of TypeScript and understand how to work with it.
There are several ways to declare types in TypeScript.
The first method we'll learn is called type inference. With type inference, you don't explicitly declare the type of a variable; instead, TypeScript automatically infers or guesses the type based on the assigned value.
For example, let's say we declare a string variable like this:
let favoriteBand = "The Red Hot Chilli Peppers";
If later on, you attempt to reassign the variable to a number, you will encounter the following error.
favoriteBand = 20
// Type 'number' is not assignable to type 'string'.
When you create a variable in TypeScript and assign it a value, TypeScript will use that value as its type. This means that TypeScript can infer the type of the variable based on the assigned value.
As mentioned in the TypeScript documentation, by understanding the behavior of JavaScript, TypeScript is able to build a type system that accepts JavaScript code while introducing types.
This allows TypeScript to "know" that the variable "favoriteBand" in the example mentioned earlier is of type string.
While this feature allows you to use TypeScript without explicitly adding type annotations, it is generally more readable and recommended to explicitly declare your types in your code.
Explicitly declaring types helps improve code clarity and enhances maintainability.
For instance, when declaring a variable:
let favoriteBand: string = "The Red Hot Chilli Peppers";
If later on, you attempt to reassign the variable to a number, you will encounter the following error.
favoriteBand = 20
// Type 'number' is not assignable to type 'string'.
An interface closely resembles a JavaScript object, but with a few key differences.
Instead of using an equal sign or commas, we utilise the "interface" keyword. Additionally, for each key in the interface, we specify its data type rather than assigning a value to it.
Subsequently, we can employ this interface as the data type for any object declaration.
interface bandName {
name: string;
country: string;
members: number;
genre: string[];
}
let bandName = {
name: "ABBA",
country: "Sweden",
members: 4,
genre: ["disco", "pop", "new wave"]
};
If, for example, you pass the members as a string instead of a number, you will encounter the following error:
let bandName: bandName = {
name: "ABBA",
country: "Sweden",
members: "4",
genre: ["disco", "pop", "new wave"]
};
// Type 'string' is not assignable to type 'number'.
If you want to make a key in an interface conditional, allowing it to be present or not, you can achieve this by adding a question mark at the end of the key in the interface.
interface bandName {
name: string;
country?: string;
members?: number;
}
If you want a variable to be capable of being assigned multiple distinct data types, you can indicate this intention by employing unions in the following manner:
interface bandName {
name: string;
country: string;
members: number | string;
}
let bandName: bandName = {
name: "ABBA",
country: "Sweden",
members: "4" // No error here :)
}
Take a look at the keyValue "members" inside the interface declaration of the variable bandName has a type declaration that accepts both numbers or strings through the logical operator |
When writing functions, we have the ability to specify the types of its parameters as well as its return value.
interface bandName {
name: string;
country: string;
members: number;
dancingQueen: (message: string) => string;
}
let bandName: bandName = {
name: "ABBA",
country: "Sweden",
members: 4,
dancingQueen: (message) => message
};
console.log(bandName.dancingQueen("Ooh, see that girl, Watch that scene, Digging the dancing queen"))
When declaring arrays, the syntax to specify their type is as follows:
numsArray: number[] = [1, 2, 3];
//In this array, only numerical values are accepted.
let numsAndStrArray: (number | string)[] = [1, "two", 3];
// Here we accept numbers and strings.
Tuples are arrays with a predetermined size and specific types assigned to each position. They can be constructed in the following manner:
let profile: [string, number];
profile = ["Benny Andersson", 3];
TypeScript checks the declared types through its compiler. A compiler is a program that converts instructions into a machine code or a lower-level form, enabling a computer to read and execute them.
When we run a TypeScript file, TypeScript compiles our code and verifies the types. Only if everything is correct, the program proceeds to execute. This allows us to detect errors before program execution.
In contrast, JavaScript performs type checking during runtime, meaning types are not checked until the program is executed.
It is worth noting that TypeScript transpiles code into JavaScript. Transpiling involves taking source code written in one language and transforming it into another language.
Although browsers cannot directly interpret TypeScript, they can execute programs written in TypeScript because the code is converted to JavaScript during the build process.
If you're using React, it's important to be aware that create-react-app offers a TypeScript template, which automatically installs and configures TypeScript for your project when it is created.
Similarly, there are templates available for Node-Express backend applications and React Native applications.
It's worth mentioning that when working with external libraries, they often provide specific types that can be installed and utilized to perform type-checking on those libraries.
Q1: What is TypeScript?
A1: TypeScript is a language that extends JavaScript by adding additional features and introducing static typing. It helps developers write more reliable and error-free code by providing a layer of safety and catching potential bugs during development.
Q2: How does TypeScript differ from JavaScript?
A2: TypeScript is a superset of JavaScript, which means that any valid JavaScript code is also valid TypeScript code. The main difference is that TypeScript introduces static typing, allowing developers to explicitly declare and enforce data types. This helps catch errors and enhances code robustness.
Q3: What are types in TypeScript?
A3: Types in TypeScript refer to the different categories or kinds of information that variables can have. They define the data type of a variable, such as string, number, boolean, object, array, or function. Typescript helps developers understand and work with these types better, improving code clarity and maintainability.
Q4: How does TypeScript improve code quality?
A4: TypeScript improves code quality by providing static typing, which allows for early detection of potential errors. It enforces type safety, catching type-related bugs during development rather than at runtime. This helps developers write more reliable and error-free code, leading to better software outcomes.
Q5: Can TypeScript be used with React?
A5: Yes, TypeScript can be used with React. In fact, create-react-app offers a TypeScript template that automatically configures TypeScript for React projects. TypeScript provides specific types for React components and libraries, enhancing type-checking and improving the development experience when working with React.
In conclusion, TypeScript offers a valuable solution for developers looking to enhance their JavaScript code quality and development experience. By introducing static typing, TypeScript helps catch potential errors and ensures more reliable and error-free code. With TypeScript, developers can enjoy the benefits of a superset of JavaScript, maintaining the familiarity and simplicity of JavaScript syntax while incorporating type declarations.
TypeScript's ability to identify and resolve issues before program execution provides a layer of safety and enhances code maintainability. Whether you're working on a small-scale project or a large-scale application, TypeScript proves to be a valuable tool for improving code robustness and productivity.
Incorporating TypeScript into your development workflow can lead to more efficient and effective coding, ultimately resulting in better software outcomes.
So why not give TypeScript a try and unlock its full potential in your next JavaScript project?
We've helped hundreds of people get a career they love. 92% hiring rate.
Our next boot camps start in August - apply today to secure a place!