TypeScript is everywhere. It has clearly won over the frontend community, and the official core team has done an impressive job with tooling and support. TypeScript is a superset of JavaScript that compiles to clean JavaScript output. TypeScript is build up on the JavaScript, and it adds advantages to the JavaScript.
Programmers have mixed opinions on it, but I've found it to be very helpful for prototyping and designing robust interfaces.
The TypeScript syntax is quite similar to JavaScript with some exceptions. So if you know the basics of JavaScript and can read the JavaScript code, you will learn Typescript very quickly.
You may have some problems wrapping your head about the idea of static types but this will go away fairly soon than you imagine.
What is the difference between JavaScript and TypeScript?
JavaScript has dynamic typing, which means that during runtime, compiler will guess the variable's type based on its value. So, if you declare a variable as a string and then assign a number/boolean to this variable, this will work and not cause an error because variable's type changes with each new value.
Typescript, on the other hand, requires you to specify the variable's type at declaration and this type cannot be changed. this is why it is called static typing.
Why is static typing significant?
Because it gives you much greater control over data that is assigned to a specific variable. The more type definitions you can put into the code, the more often you will start noticing that it is saving you from wasting time on manually debugging bugs in the console. Having type definitions in your code not only helps programmer productivity but also helps interpreters and compilers to optimize the running of your code. You will be starting to appreciate the types as you code and work with front-end developers. You will see it in action when you'll start using Typescript.
Local setup - Installing and running typescript on a local computer
- First install Node from nodejs.org
- npm install -g typescript
- Create typescript file, example- index.ts
Variable Types
Compile time type-checking is one of the most significant features of TypeScript. It lets us catch errors related to the types of data at compile time.
let firstName: string;
let age: number;
let isMarried: boolean;
Here we have types attached to all the variables. If we try to put a string value in place of a number type variable, TypeScript will catch it at compile time.
Multiple types
In TypeScript, we keep a single type for a variable but that is not possible every time. So, instead, TypeScript provides us with the any
type. This means we can assign multiple types of values to one variable.
let myVariable: any = 'Hello World';
myVariable = 10;
myVariable = false;
Above, we’ve declared myVariable with any type. First we assigned it a string, next a number, and finally a boolean. This is possible because of the any type
Sub types
Sub types are used when we are unaware of the value of the variable. TypeScript provides us with two sub types: null and undefined.
let myVariable: number = undefined;
The variable myVariable has been assigned the value of undefined because, at this point in time, we don’t know what it is going to be. We can also use null here.
Implicit vs explicit typing
In the examples above, we saw explicit types where we set the type of the variable. Implicit typing, on other hand, is performed by the compiler without us stating the variable type.
let name = 'Hello World';
we have not assigned any type to the variable. We can check the type of this variable using thetypeof function. This will show that name is of string type because the compiler took care of the typing.
Checking types
In this lesson, we’ll learn how we can check the type of a variable, and catch any error or perform any operation. It uses an example in which we test if our variable is of type Bear (where Bear is a class). If we want to check the type of our variable, we can use theinstanceof method.
import { Bear } from 'file.ts';
let bear = new Bear(3);
if (bear instanceof Bear) {
//perform some operation
}
Type assertions
Type assertion means we can cast a variable to any particular type, and we tell TypeScript to handle that variable using that type. Let’s try to understand it with an example:
let variable1: any = 'Hello World';
if ((variable1 as string).length) {
//perform some operation
}
variable1 has the type of any . But, if we want to check its length, it will produce an error until we tell TypeScript to handle it as a string.
Arrays
In JavaScript, when we assign values to an array, we can put in different types of items. But, with TypeScript, we can declare an array with types as well.
let array1: number[] = [1, 2, 3, 4, 5];
In the above example, we declared an array of numbers by assigning it the number type. Now TypeScript will make sure the array contains only numbers.
Tuples
Sometimes we need to store multiple types of values in one collection. Arrays will not serve in this case. TypeScript gives us the data type of tuples. These are used to store values of multiple types.
let tuple_name = [10, 'Hello World'];
This example shows that we can have data items of number and string types in one collection.
Parameters
Using TypeScript, we can also assign types to the parameters of a function. This is a very useful way to handle errors regarding data type in a function.
const multiply = (num1: number, num2: number) => {
return num1 * num2;
}
We have declared a function multiply which takes two parameters and returns the value from multiplying them. We added a type of number to both the parameters so that no other value except a number can be passed to them.
Return types
Like parameters, we can also add type-checking to the return value of a function. This way we can make sure that the return value from a function has an expected type.
const multiply = (num1: number, num2: number): number => {
return num1 * num2;
}
We have added a return type of number to the function. Now, if we return anything except a number, it will show us an error.
Custom types
In TypeScript, we can create a custom type using the keyword of type. We can then type-check objects on the basis of that type.
type person = {firstName: string};
const example3: person = {firstName: 'Dollan'};
These are the basics of type system. If you're interested in getting started with Typescript below are some of free resources to help you get started:
TypeScript Course for Beginners - Learn TypeScript from Scratch!
Typescript's Official Documentation
Happy learning :)