Back to Overview

TypeScript

javascript frontend language programming

What is TypeScript?

TypeScript is a safer version of JavaScript that helps catch mistakes before your program runs. It adds labels (called types) to your data so the computer can check if you’re using the right kind of information in the right places.

Simple Analogy

Think of TypeScript like a kitchen with labeled containers:


  • JavaScript (Regular Kitchen): Like having containers without labels. You might put flour in a container thinking it’s sugar, and only discover the mistake when you try to bake cookies.

  • TypeScript (Labeled Kitchen): Like having containers with clear labels that tell you exactly what should go inside:
    • Each container has a specific label (type definition)
    • The kitchen system checks if you’re putting the right ingredients in the right containers (type checking)
    • If you try to put flour in a container labeled ‘sugar’, you get a warning (compile-time error)
    • The final result is still the same food that anyone can eat (compiles to standard JavaScript)

Key Concepts

  • Types: Labels that tell you what kind of data something is (like ‘string’ for text, ‘number’ for numbers)
  • Type Checking: Making sure you’re using the right kind of data in the right places
  • Interfaces: Templates that define what properties an object should have
  • Generics: Ways to create reusable code that works with different types of data
  • Type Inference: When TypeScript automatically figures out what type something is
  • Compilation: Converting TypeScript code into JavaScript that browsers can run

Example

// Define what a user should look like
interface User {
  name: string;
  age: number;
  email: string;
}

// Function that works with a specific type of data
function greetUser(user: User): string {
  return `Hello, ${user.name}! You are ${user.age} years old.`;
}

// Create a user with the right properties
const myUser: User = {
  name: "John",
  age: 30,
  email: "john@example.com"
};

// This works fine
console.log(greetUser(myUser));

// This would cause an error because 'age' is missing
const badUser = {
  name: "Jane",
  email: "jane@example.com"
};
// TypeScript would warn: Property 'age' is missing in type...