DEV Community

Cover image for Introduction to TypeScript
shivlal kumavat
shivlal kumavat

Posted on

Introduction to TypeScript

1.Introduction

Typescript is superset of Javascript means TypeScript is a new way to write JavaScript. TypeScript was developed by Microsoft in 2012 for the extensive community of JS developers easy access to a statically typed(strict declaration) language.

2.Install TypeScript

Install TypeScript using Node.js Package Manager (npm) By using the following command in the Terminal Window.

npm install typescript -g //Install as a global module

npm install typescript@latest -g //Install latest if you have an older version

3.Variable types

Compile time type-checking is one of the most important features of TypeScript. It lets us catch errors related to the types of data at compile time. This lesson explains the data types available in TypeScript.

let name: string;
let age: number;
let isActive: boolean;
Enter fullscreen mode Exit fullscreen mode

You can see how 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.

4. Any types

Any type is used when we do not know about the type of value and we want to skip the type-checking on compile time. This is also known as Multiple types because we can assign multiple types of values to one variable.

let myValue: any = 'Hello IT jugadu';  
myValue = true;  // Correct
myValue = 855; // Correct
Enter fullscreen mode Exit fullscreen mode

In the above example, we declared myValue with any type. First we assigned it a string, next a boolean, and finally a number. This is possible because of any type.

5. Null and Undefined type

This is used when we do not know about the value of the variable.
let myValue: string = null;

The variable myValue has been assigned the value of null because, at this point in time, we don’t know what it is going to be. We can also use undefined here.

6.Type assertions

Type assertion allows you to set the variable to any particular type and tell the compiler to handle that variable using that type.

let age: any = 22; 
let studentAge = <number> age; console.log(typeof(studentAge));  // O/P: number
Enter fullscreen mode Exit fullscreen mode

Type Assertion with Object
It might happen most of the time when we are porting over code from JavaScript to TypeScript.
For example we take below code:

var teacher= {};
teacher.name = 'IT jugadu'; // Error: property 'name' does not exist on `{}`
teacher.isMarried = true; // Error: property 'isMarried' does not exist on `{}`

teacher.salary = 18000; // Error: property 'salary' does not exist on `{}`


interface Teacher { 
  name: string;
  isMarried: boolean; 
  salary: number; 
} 
let teacher = <Teacher> { }; 
teacher.name = "IT jugadu"; // Correct
teacher.isMarried = true; // Correct
teacher.salary = 18000; // Correct
Enter fullscreen mode Exit fullscreen mode

7. Arrays

TypeScript supports arrays, similar to JavaScript. There are two ways to declare an array:

  1. With square brackets.

let arrayVar: number[] = [8, 3, 9, 1, 5];

  1. With generic array type, Array<elementType>.

let student: Array<string> = ['Raj', 'Ravi', 'IT jugadu'];

8.Tuples

TypeScript introduced a new data type called Tuple,These are used to store values of multiple types. because sometimes we need to store multiple types of values in one collection. Arrays will not serve in this case.

let myTuple = ['Welcome to IT jugadu', 22, false];

In example, it shows that we can have data items of number,string and boolean types in one collection.

9.Enums

Enums stands for Enumerations. It is used to define the set of named constants Like other language Java and C#, We can define the enums by using the enum keyword.

There are three types of Enums in TypeScript.

  • Numeric Enums
  • String Enums
  • Heterogeneous Enums

Numeric Enums
Numeric enums are number-based enums, which store values as numbers.

enum AsciiValue {  
  w=119, 
  x=120, 
  a=97, 
  z=122
}
Enter fullscreen mode Exit fullscreen mode

String Enums

String enums are the same as numeric enums, except that the enum values are initialized with string values rather than numeric values.

enum City{   
  Surat = "Surat",       
  Mumbai = "Mumbai",       
  Jaipur= "Jaipur"
}
Enter fullscreen mode Exit fullscreen mode

Heterogeneous Enum

These enums contain both string and numeric values.

enum Status { 
  Active = 'ACTIVE', 
  Deactivate = 1, 
  Pending 
}
Enter fullscreen mode Exit fullscreen mode

10.Object

An object is an instance which contains set of key value pairs.

var student= { 
  firstName:"Raj", 
  lastName:"Ravi" 
};
//access the object values 
console.log(student.firstName)
console.log(student.lastName)
Enter fullscreen mode Exit fullscreen mode

11.Union

Two or more data types are combined using the pipe symbol (|) to denote a Union Type.

var myValue:string|number;
myValue = 52
console.log("Here is number :"+ myValue)  
val = "Welcome to IT jugadu"  
console.log("Here is string :"+ myValue)
Enter fullscreen mode Exit fullscreen mode


O/P:
Here is number :52
Here is string : Welcome to IT jugadu

12.Parameterized Function with Type

Parameters are values or arguments passed to a function. In TypeScript, the compiler expects a function to receive the exact number and type of arguments as defined in the function signature.

function welcome(mayVal: string, name: string ) { 
  return mayVal + ' ' + name + '!'; 
} 
Enter fullscreen mode Exit fullscreen mode


welcome('Welcome to ’,'IT jugadu'); //Correct
O/P: "Welcome to IT jugadu!"

We have declared a function welcome which takes two parameters. We added a type of string to both the parameters so that no other value except a string can be passed to them.

13.Return types

Using Typescript we can add type-checking to the return value of a function. By this we can make sure that the return value from a function has an expected type.

function welcome(mayVal: string, name: string ) : string { 
 return mayVal + ' ' + name + '!'; 
} 
Enter fullscreen mode Exit fullscreen mode


welcome('Welcome to ’,'IT jugadu'); //Correct
O/P: "Welcome to IT jugadu!"

14: Interfaces

The interface defines the syntax that any entity must adhere to. Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members.

interface IStudent {
  firstName:string,
  lastName:string, 
  welcome: ()=>string
}
Enter fullscreen mode Exit fullscreen mode

Use of Interface and Objects

var student:IStudent = { 
   firstName:"Raj",
   lastName:"Ravi", 
   welcome: ():string =>{ return "Welcome to IT jugadu!" } 
}

console.log(“Student details”) 
console.log(student.firstName) // O/P: Raj
console.log(student.lastName)  // O/P: Ravi
console.log(student.welcome())  // O/P: Welcome to IT jugadu!
Enter fullscreen mode Exit fullscreen mode

15.Namespaces

In typescript, namespace is used for logical grouping of functionalities.This includes interfaces, classes, functions and variables to support a single or a group of related functionalities.

16.Models

Sometimes we are getting a number of problems when using the interface. Like interfaces do not keep the default value as well as can’t embed anything coming from the server side. To resolve this issue we are using Models.

17.Generics

In typescript, by using Generics we can create the reusable component. This component works with multiple data types rather than the single data types.

18.Conclusions and resources

Thanks for reading and great job on following the guide, I hope you're now ready to use TypeScript in your projects!

In this TypeScript blog you learned about the fundamentals of typescript.

If you want to stay updated on TypeScript I suggest the following blog.

The official TypeScript blog where you can learn about the new releases and features.

Thanks again for reading and stay tuned!

Happy coding!!!

Top comments (0)