Introduction to Types in TypeScript

TypeScript, an open source language, is a typed superset of JavaScript that compiles to plain JavaScript. It adds optional static typing and class-based object oriented programming to the language.

Introduction

 
TypeScript, an open-source language, is a typed superset of JavaScript that compiles to plain JavaScript. It adds optional static typing and class-based object-oriented programming to the language. Some of the key features it provides are type support and code encapsulation.
 

Overview of the relation between TypeScript and JavaScript

  
TypeScript1.png
  
As in the above figure, MathCalculator.ts is a TypeScript file that is compiled by tsc, the TypeScript compiler, to the MathCalculator.js file. Then one can use this MathCalculator.js in their application.
 

OOPS Features of TypeScript

  1. SupportsKey JavaScript Features
  2. Providesstatic typing
  3. Supportsconstructors, properties and functions
  4. DefineInterfaces
  5. Encapsulation through classes and modules
  6. Supportlambdas => 

TypeScript Annotations

 
TypeScript2.png
 
Primitive Types
 
Basic primitive types are number, bool, string, null and undefined.
 
TypeScript8.png.jpg
  
Object Types
 
Object literals
 
TypeScript4.png
 
Functions
 
Here functions can be used in the following two ways:
  1. Assigning thefunction directly
  2. Defining a type as afunction and then assign a function
 
TypeScript5.png
 
Arrow function expressions
 
TypeScript6.png
 
Equivalent JavaScript code
 
TypeScript7.png
 
Dynamic and Static typing 
 
TypeScript
JavaScript
Static typing isoptional here
Only dynamictyping is supported
Type safety ischecked at compile time
Type safety ischecked at run time
 

Summary

 
In this article, we have seen that TypeScript *.ts files are compiled to *.js files by the TypeScript compiler (tsc). Also, we have seen annotations and various object types available in TypeScript. In future articles, we will explore classes, interfaces, and modules.