📘

Introduction to TypeScript Basics

Apr 26, 2025

Introduction to TypeScript

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

Installing TypeScript

  1. Install TypeScript:
    • Command: npm install typescript -D
  2. Initialize a configuration file:
    • Command: npx tsc --init

Understanding the TS Configuration File

  • The tsconfig.json file contains several important fields:
    • compilerOptions: Customizable settings for TypeScript.
      • target: Specifies the JavaScript version (e.g., ES2020, ESNext).
      • module: Default is CommonJS, can switch to ESNext or ES6.
      • esModuleInterop: Smoothes compatibility between module systems.
      • forceConsistentCasingInFileNames: Ensures case-sensitive imports.
      • strict: Enables strict type checking.
      • skipLibCheck: Skips type checking for library files to speed up compilation.

Using TypeScript for User Input Validation

  • Example: Create a user registration form.
    • Ensure input values are of the correct type (e.g., name should be a string).
  • TypeScript catches errors like passing a number when a string is expected.

Working with Variables

  • Variable Types:
    • Strings, numbers, booleans, arrays.
    • Example: A discount variable should only accept numbers to prevent revenue loss.
  • Union Types: Allow a variable to accept multiple types (e.g., string | number).
    • Useful for situations like tracking top-selling products which could be strings or numbers.

Functions in TypeScript

  • Ensure function inputs and outputs have the correct type.
    • Example: Loan calculation function that only accepts numbers.
    • Use type annotations to enforce return types, preventing bugs.

Working with Objects and Interfaces

  • Use Interfaces to define the structure of objects (e.g., employee data) to ensure consistency.
    • Make properties optional using a question mark (e.g., position?).

Type Aliases and Literal Types

  • Type Aliases: Give a new name to a type, enhancing readability.
    • Example: Alias for username.
  • Literal Types: Restrict a type to specific string values (e.g., roles like "admin", "user").

Enums in TypeScript

  • Define named constant values for better readability and error prevention.
    • Example: Subscription tiers or HTTP status codes.

Generics in TypeScript

  • Generics: Create reusable components that work for multiple data types.
    • Example: Generic function identity ensuring input and output types match.
    • Acts as a placeholder (e.g., T) for type safety.

Conclusion

  • This overview covers the basics of TypeScript.
  • More advanced features will be discussed in future videos.
  • PDF version of the content available for reference.
  • Encourage viewers to subscribe for more learning resources.