Introduction to Types in TypeScript

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. Supports Key JavaScript Features
  2. Provides static typing
  3. Supports constructors, properties and functions
  4. Define Interfaces
  5. Encapsulation through classes and modules
  6. Support lambdas => 

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 the function directly
  2. Defining a type as a function 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 is optional here
Only dynamic typing is supported
Type safety is checked at compile time
Type safety is checked 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.


Similar Articles