Over the past few years now, TypeScript has become one of the most popular programming languages for web developers.
Its rise in popularity can be attributed to the many benefits it offers over traditional JavaScript.
In this article series, I will cover the fundamental concepts of TypeScript, including its syntax, data types, functions, classes, and modules.
In the upcoming part of this article, I will explore how you can implement it in medium to large-scale or enterprise-level applications.
What is Typescript:
TypeScript is a popular open-source programming language that extends the capabilities of JavaScript. It is a typed superset of JavaScript, which means that it includes all of the features of JavaScript and provides additional features for static typing, classes, interfaces, and modules.
Lets take a look at why developers want types in their application code.
Take a look at this sample JavaScript code for example;
In this sample code, we can't really ascertain whether the argument to be passed into the function are numbers or string or both.
What if someone who interpreted a and b as numbers made this “backwards-compatible change?” like this
We’re headed for trouble if we decided to pass strings in for a and b
Lets take a look at the typescript version of this code:
Here, we've added type annotations to the function parameters a and b, as well as the return type of the function.
By specifying that a and b are of type number, TypeScript ensures that only numerical values can be passed to the function as arguments, and it will throw a compilation error if any other type is used.
Getting Started with TypeScript
To start using TypeScript, you first need to install it on your machine. TypeScript can be installed using the Node Package Manager (npm) by running the following command in your terminal:
npm install -g typescript
Setting up a simple Typescript project:
For a basic "Hello, Typescript!" TypeScript program, you can follow these steps:
1-Create a new directory for your project and navigate into it:
`mkdir hello-typescript
cd hello-typescript`
2- Initialize a new package.json file for your project:
npm init -y
3- Install TypeScript as a development dependency:
npm install typescript
4 -Create a new file called index.ts in the root of your project directory and add the following TypeScript code to it:
This code declares a variable called message of type string and assigns it the value "Hello, World!". It then logs the value of message to the console.
Compile the TypeScript code to JavaScript using the tsc command:
npx tsc index.ts
A new index.js is create upon compilation
Variables and Values:
In TypeScript, variables are used to store values that can be used later in the program. Like in JavaScript, TypeScript has several types of variables, including var, let, and const, each with their own properties and uses.
Let's take a look at how we can define and assign values to variables in TypeScript:
In the above code examples, the var
keyword is used to define and initialize the age variable, which is assigned the numerical value 1.
The let
keyword is used to define the name variable, which is later assigned the string value "James Bond".
Finally, the const
keyword is used to define and initialize the pi constant variable, which is assigned the numerical value 3.142.
If we try to give age a value that is incompatible with number, we get an error:
let age: number = 18
age = "not a number"
Implicit any and type annotations:
Variables and function parameters can have either an explicit type annotation or an implicit type of any.
An explicit type annotation is when you specify the type of a variable or function parameter explicitly in the code. For example:
In this example, myString
has an explicit type annotation of string, and the addNumbers
function has explicit type annotations for its parameters x and y, as well as its return type.
On the other hand, an implicit type of any
is used when the type of a variable or function parameter is not specified explicitly. For example:
In this example, myVariable
has an implicit type of any because its type is not specified explicitly. Similarly, the addValues
function has implicit types of any for its parameters a and b.
Function arguments and return values
To explain this, lets observe this javascript code
Here, it’s not clear, even from the implementation of the function, whether add should accept numbers or strings.
Here’s what your in-editor tooltip would look like if you were using this function:
Without type annotations, “anything goes” for the arguments passed into add.
Let’s add some type annotations to our function’s arguments:
In typescript, we can add type annotations to function arguments and return values to make our code more type-safe and catch errors at compile-time. Here is an example:
In this example, the addNumbers
function takes two arguments x and y, both of which have a type of number. The function also has a return type of number.
If we don't supply the right type, we get an error like this
If we wanted to specifically state a return type, we could do so using the : syntax in one more place
This is a great way for code authors to state their intentions up-front.
TypeScript will make sure that we live up to this intention, and errors will be surfaced at the location of the function declaration instead of where we use the value returned by the function.
Objects, Arrays and Tuples:
Now that we know how to type simple variables and functions, let’s make things a bit more interesting with collections. In JavaScript, this means Objects and Arrays.
In TypeScript, Objects, Arrays, and Tuples are three common data structures used for storing and manipulating data.
Objects:
Objects in TypeScript are similar to objects in JavaScript. They are used to store key-value pairs, where the keys are strings and the values can be any data type.
Objects are defined using curly braces {}
and the key-value pairs are separated by colons :.
Here's an example of how to define an object in TypeScript:
In the example code above, we define an object named person with three properties: name, age, and isStudent. We can access the properties of the person object using dot notation like this.
console.log(person.name); // Output: James
Arrays:
Arrays in TypeScript are used to store a collection of values of the same data type. They are defined using square brackets []
and the values are separated by commas.
Here's an example code:
// Define an array
let numbers: number[] = [1, 2, 3, 4, 5];
In the example above, we define an array named numbers with five elements of type number.
We can access the elements of the numbers array using square bracket notation like this.
console.log(numbers[1]); // Output: 2
Tuples:
Tuples in TypeScript are used to store a fixed number of values of different data types.
They are defined using square brackets []
and the data types of the values are specified in order, separated by commas.
Here's an example:
// Define a tuple
let employee: [string, number] = ['James', 27];
In the example code above, we define a tuple named employee with two elements: a string for the employee name and a number for the employee age.
We can access the elements of the employee tuple using square bracket notation like this.
console.log(employee[0]); // Output: James
This article continues in In part 2.....here
Top comments (0)