🚀

Getting Started with TypeScript Basics

Apr 26, 2025

Introduction to TypeScript

  • TypeScript is a syntactic superset of JavaScript.
  • Adds static typing to prevent common coding mistakes.
  • Catches errors during development that JavaScript wouldn't.
  • Acts like a buddy to double-check your work.

Setting Up TypeScript

  1. Installation

    • Run in terminal: npm install typescript --save-dev
  2. Initialize Configuration

    • Command: npx tsc --init
  3. TS Config File

    • Contains various compiler options.
    • Compiler Options:
      • Target: Selects JavaScript version (e.g., ES2020).
      • Module: Default is CommonJS; can use ES6 or ESNext.
      • ES Module Interop: Smoothes compatibility issues.
      • Force Consistent Casing in File Names: Ensures case sensitivity.
      • Strict: Enables strict type-checking.
      • Skip Lib Check: Skips type-checking for library files.

Basic TypeScript Usage

Variable Types

  • String Variable Example:

    • For user registration, declare: let name: string = 'John Doe';
    • TypeScript catches errors if non-string values are assigned.
  • Number Variable Example:

    • For discounts: let discount: number;
    • Ensures only numbers are accepted, preventing revenue loss.
  • Boolean Variable Example:

    • Feature toggle for beta users: let isBetaUser: boolean;

Arrays

  • String Array Example:

    • Use let topSellers: string[]; to restrict array values.
  • Union Type for Arrays:

    • let topSellers: (string | number)[];
    • Allows both strings and numbers in the array.

Functions

  • Function Example: Loan Calculation
    • Function signature: function calculateLoan(amount: number, rate: number): number {}
    • TypeScript ensures both inputs and output are numbers.

Working with Objects

  • Interfaces:

    • Define structure of objects (e.g., employee data).
    • Example: interface Employee { id: number; name: string; position?: string; // Optional property }
    • Ensures consistency in object structure.
  • Type Aliases:

    • Create custom types for clarity (e.g., type Username = string;).
    • Can restrict to specific values using literal types (e.g., type Role = 'admin' | 'user';).

Enums

  • Enums in TypeScript:
    • Define named constant values (e.g., Subscription tiers).
    • Example: enum Subscription { Free, Basic, Premium }
    • Improves readability and reduces errors.

Generics

  • Generics Overview:
    • Create reusable components that work with multiple data types.
    • Example: function identity<T>(arg: T): T { return arg; }
    • Ensures type safety by making types consistent between input and output.

Conclusion

  • This is just the basics of TypeScript.
  • Advanced features will be covered in future videos.
  • Free PDF version available; support the channel by subscribing.