TypeScript Basics

The Type-Safe JavaScript Super-set


TypeScript is an open-source programming language developed and maintained by Microsoft. It operates as a strict syntactical superset of JavaScript, meaning that any valid JavaScript code is also valid TypeScript code.

TypeScript introduces static typing to the JavaScript ecosystem. Because browser engines cannot execute TypeScript files directly, a command-line tool called the TypeScript Compiler (tsc) strips away all type annotations, transforming the codebase into clean, standard JavaScript that can run inside any browser or Node.js environment.


Primitive and Explicit Type Annotations

In JavaScript, variables are dynamically typed—a variable can hold a string, and on the next line be overwritten with a number, which frequently causes runtime errors. TypeScript locks down variable assignments using explicit type annotations.


// Explicit type declarations
let siteName: string = "Careeroza";
let activeUsers: number = 2000;
let isLaunching: boolean = true;
let dynamicData: any = "This bypasses type checking entirely";

// Type Inference (TypeScript automatically figures out the type)
let platformType = "MERN Stack"; // Inferenced as a string
// platformType = 105; // Errors out: Type 'number' is not assignable to type 'string'.


Complex and Structured Data Types

Beyond simple primitives, TypeScript allows you to define rigid shapes for complex data collections like arrays, tuples, and custom structures.


Arrays and Tuples


// Defining an array containing strictly numbers
let performanceMetrics: number[] = [85, 92, 78, 95];

// Declaring a Tuple (an array with a fixed number of elements and predefined positions)
let userToken: [number, string];
userToken = [1024, "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"]; // Correct syntax
// userToken = ["text", 1024]; // Errors out due to mismatched positions


Enums (Enumerations)

Enums allow you to define a collection of named constants, making conditions and structural flags clean and readable.


enum UserRole {
  Admin,     // Automatically assigned 0
  Mentor,    // Automatically assigned 1
  Student    // Automatically assigned 2
}

let currentViewer: UserRole = UserRole.Student;


Object Blueprints: Interfaces vs. Type Aliases


To enforce strict formatting rules on JavaScript objects, you can declare custom schemas using Interfaces or Type Aliases.

[Image diagram showing the structural similarities and differences between TypeScript Interfaces and Type Aliases]


// Enforcing structural shape using an Interface
interface Company {
  readonly companyName: string; // Immutability rule (cannot be modified after creation)
  employeeCount: number;
  websiteDomain?: string;       // Optional property flag (indicated by the '?')
}

const startup: Company = {
  companyName: "THARUN plc",
  employeeCount: 2
};
// startup.companyName = "New Name"; // Errors out: Cannot assign to 'companyName' because it is a read-only property.


The Key Architectural Difference

  • Interfaces are primarily designed to define the shape of objects and allow for data declaration merging (you can re-open an interface to add properties later).

  • Type Aliases (type) are highly versatile and can represent primitive definitions, unions, tuples, or complex mapping logic directly.

Advanced Type Combinations: Unions and Intersections

TypeScript features unique operational logic allowing you to build highly dynamic layouts out of separate structural baselines.


Union Types (OR logic)

Enables a variable, argument, or array to accept multiple distinct types seamlessly.

let serverResponseCode: string | number;
serverResponseCode = 200;       // Valid assignment
serverResponseCode = "SUCCESS"; // Valid assignment


Intersection Types (AND logic)

Combines multiple existing interfaces or types into a singular, integrated compound structure.


interface Developer {
  primaryStack: string[];
}

interface Founder {
  equityPercentage: number;
}

// Creating a unified structure combining both interface layers
type TechFounder = Developer & Founder;

const founderProfile: TechFounder = {
  primaryStack: ["MongoDB", "Express", "React", "Node.js"],
  equityPercentage: 50
};

Function Signatures and Strict Contracts

TypeScript lets you establish clear architectural contracts for function execution loops, explicitly locking down inputs (parameters) and outputs (return values).



// Function specifying strict parameter types and an explicit return type
function calculateTargetGrowth(currentFollowers: number, multiplier: number): number {
  return currentFollowers * multiplier;
}

// Function that performs actions but explicitly returns nothing
function logSystemAction(message: string): void {
  console.log(`[SYSTEM LOG]: ${message}`);
}

calculateTargetGrowth(2000, 7.5); // Returns 15000
// calculateTargetGrowth("2000", 7.5); // Errors out before compilation due to type mismatch