What is TypeScript?

TypeScript is JavaScript with types. It helps catch errors before you run your code, making development safer and faster.

The Simple Explanation

Imagine you're baking:

  • JavaScript: You can mix any ingredients without checking. Sometimes you accidentally use salt instead of sugar and only find out when you taste it!
  • TypeScript: Someone checks your ingredients before you mix them. "Hey, that's salt, not sugar!" Problem solved before baking!

TypeScript catches mistakes while you write code, not after you run it.

JavaScript vs TypeScript

JavaScript (Without Types)

function greet(name) {
  return "Hello, " + name.toUpperCase();
}

greet("Alex");        // ✅ Works: "Hello, ALEX"
greet(123);           // ❌ Crashes! Numbers don't have .toUpperCase()
greet();              // ❌ Crashes! undefined doesn't have .toUpperCase()

You only discover these errors when the code runs!

TypeScript (With Types)

function greet(name: string) {
  return "Hello, " + name.toUpperCase();
}

greet("Alex");        // ✅ Works: "Hello, ALEX"
greet(123);           // ❌ ERROR: Type 'number' is not assignable to type 'string'
greet();              // ❌ ERROR: Expected 1 argument, but got 0

VS Code shows red squiggly lines before you even run the code!

Why We Use TypeScript

1. Catch Errors Early

Problem without TypeScript:

const user = { name: "Alex", age: 25 };
console.log(user.email); // undefined (typo: should be user.name?)

No error! Just silently gives you undefined.

Solution with TypeScript:

const user = { name: "Alex", age: 25 };
console.log(user.email); // ❌ ERROR: Property 'email' does not exist

TypeScript immediately tells you the problem!

2. Better Autocomplete

VS Code knows what properties and methods are available:

const user = {
  name: "Alex",
  age: 25,
  email: "alex@example.com"
};

user. // ← VS Code suggests: name, age, email

No more guessing or looking up documentation!

3. Self-Documenting Code

// Without types - what does this function expect?
function createUser(name, age, admin) {
  // ...
}

// With types - crystal clear!
function createUser(name: string, age: number, admin: boolean) {
  // ...
}

You know exactly what to pass without reading documentation!

4. Refactoring Confidence

Change a function's parameters? TypeScript shows you every place that needs updating. No more hunting through files wondering what broke!

Basic TypeScript Syntax

Primitive Types

let name: string = "Alex";
let age: number = 25;
let isStudent: boolean = true;
let nothing: null = null;
let notDefined: undefined = undefined;

Arrays

let numbers: number[] = [1, 2, 3];
let names: string[] = ["Alex", "Sam", "Jordan"];

Objects

let user: {
  name: string;
  age: number;
} = {
  name: "Alex",
  age: 25
};

Functions

// Specify parameter types and return type
function add(a: number, b: number): number {
  return a + b;
}

// Arrow function
const multiply = (a: number, b: number): number => {
  return a * b;
};

Optional Properties

function greet(name: string, greeting?: string) {
  if (greeting) {
    return `${greeting}, ${name}!`;
  }
  return `Hello, ${name}!`;
}

greet("Alex");              // ✅ Works
greet("Alex", "Welcome");   // ✅ Also works

The ? means "optional".

Interfaces and Types

For complex objects, define reusable types:

Interface

interface User {
  name: string;
  age: number;
  email: string;
}

const user: User = {
  name: "Alex",
  age: 25,
  email: "alex@example.com"
};

Type Alias

type User = {
  name: string;
  age: number;
  email: string;
};

const user: User = {
  name: "Alex",
  age: 25,
  email: "alex@example.com"
};

For simple cases, interface and type are interchangeable. Our codebase uses both.

TypeScript in React

Component Props

interface ButtonProps {
  text: string;
  onClick: () => void;
  disabled?: boolean;
}

function Button({ text, onClick, disabled }: ButtonProps) {
  return (
    <button onClick={onClick} disabled={disabled}>
      {text}
    </button>
  );
}

// Usage
<Button text="Click me" onClick={() => console.log("Clicked!")} />

Now you know exactly what props the component accepts!

State Types

const [count, setCount] = useState<number>(0);
const [name, setName] = useState<string>("");
const [user, setUser] = useState<User | null>(null);

Real Example from Our Codebase

From components/layout/Header.tsx:

interface HeaderProps {
  transparent?: boolean;
}

export default function Header({ transparent = false }: HeaderProps) {
  return (
    <header className={transparent ? "bg-transparent" : "bg-white"}>
      {/* ... */}
    </header>
  );
}

What this tells us:

  • Header accepts one prop: transparent
  • transparent is optional (the ?)
  • It's a boolean type
  • Default value is false

Crystal clear without reading the entire component!

Common TypeScript Patterns in Our Codebase

1. React Component Props

interface ComponentProps {
  title: string;
  description?: string;
  children: React.ReactNode;
}

2. Event Handlers

const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
  console.log("Clicked!");
};

const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  console.log(event.target.value);
};

3. Array of Objects

interface NavItem {
  name: string;
  href: string;
}

const navItems: NavItem[] = [
  { name: "Home", href: "/" },
  { name: "About", href: "/about" }
];

What You Don't Need to Know (Yet)

TypeScript has many advanced features. For our codebase, skip these:

  • ❌ Generics (beyond basic React types)
  • ❌ Utility types (Partial, Pick, Omit, etc.)
  • ❌ Decorators
  • ❌ Namespaces
  • ❌ Advanced type manipulation

Focus on:

  • ✅ Basic types (string, number, boolean)
  • ✅ Interfaces for object shapes
  • ✅ Function parameter types
  • ✅ React component props types

That covers 95% of what you'll see!

When TypeScript Complains

"Type 'X' is not assignable to type 'Y'"

Meaning: You're trying to use the wrong type

let age: number = "25"; // ❌ ERROR: string is not a number

let age: number = 25;   // ✅ Fixed

"Property 'X' does not exist on type 'Y'"

Meaning: You're trying to access something that doesn't exist

const user = { name: "Alex" };
console.log(user.age); // ❌ ERROR: Property 'age' does not exist

// Fix: Either add the property or check your typo

"Expected N arguments, but got M"

Meaning: Wrong number of function arguments

function greet(name: string, greeting: string) { }

greet("Alex");              // ❌ ERROR: Expected 2 arguments, got 1
greet("Alex", "Hello");     // ✅ Fixed

Tips for Working with TypeScript

1. Let TypeScript Infer When Possible

// Unnecessary (TypeScript already knows)
let name: string = "Alex";

// Better (TypeScript infers it's a string)
let name = "Alex";

2. Use the any Type Sparingly

let data: any = "anything"; // ❌ Defeats the purpose of TypeScript

let data: string = "specific type"; // ✅ Better

any disables type checking. Only use it when absolutely necessary!

3. Read Error Messages Carefully

TypeScript errors can be verbose, but they usually tell you exactly what's wrong:

Type '{ name: string; }' is not assignable to type 'User'.
  Property 'age' is missing in type '{ name: string; }' but required in type 'User'.

Translation: "You forgot to include age!"

4. Hover in VS Code

Hover over variables, functions, or types to see their definitions. This is super helpful!

TypeScript Configuration

Our project has TypeScript configured in tsconfig.json. You don't need to modify this, but it's good to know:

{
  "compilerOptions": {
    "strict": true,        // Strict type checking
    "target": "ES2017",    // JavaScript version to compile to
    "lib": ["dom", "ES2017"], // Available features
    "jsx": "preserve",     // Keep JSX for Next.js
    // ... more settings
  }
}

"strict": true means TypeScript is extra careful. This is good! It catches more bugs.

Common Questions

Q: Do I need to learn all of TypeScript?

A: No! Basic types and interfaces are enough. Learn advanced features only when you need them.

Q: Can I write JavaScript in a TypeScript file?

A: Yes! TypeScript is a superset of JavaScript. All JavaScript code is valid TypeScript. You can gradually add types.

Q: What if I get stuck on a TypeScript error?

A:

  1. Read the error message carefully
  2. Try copying the error to Google
  3. Ask for help (see Getting Help)
  4. As a last resort, use any (but try to fix it later!)

Q: Is TypeScript harder than JavaScript?

A: There's a small learning curve, but it actually makes coding easier because:

  • Autocomplete is better
  • Errors are caught earlier
  • Code is more self-documenting

External Resources

Essential Reading

TypeScript Handbook: https://www.typescriptlang.org/docs/handbook/intro.html

  • What it is: Official TypeScript documentation
  • When to use: Reference when you encounter unfamiliar syntax
  • Start with: "The Basics" and "Everyday Types" sections

TypeScript for JavaScript Programmers: https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html

  • What it is: Quick 5-minute intro
  • When to use: Fast overview before diving into code
  • Time: 5 minutes

Interactive Learning

TypeScript Playground: https://www.typescriptlang.org/play

  • What it is: Online TypeScript editor with live error checking
  • When to use: Experiment with TypeScript without setting up a project
  • Tip: Try pasting code examples to see how they work!

Scrimba - Learn TypeScript: https://scrimba.com/learn/typescript

  • What it is: Interactive TypeScript course
  • When to use: If you want structured, hands-on learning
  • Time: 1-2 hours

Video Learning

TypeScript Crash Course by Traversy Media: https://www.youtube.com/watch?v=BCg4U1FzODs

  • What it is: 50-minute video covering TypeScript basics
  • When to use: If you prefer video learning
  • Time: 50 minutes

Summary

TypeScript is:

  • JavaScript with type checking
  • Catches errors before you run code
  • Provides better autocomplete and documentation

Key concepts:

  • Primitive types: string, number, boolean
  • Interfaces: Define object shapes
  • Function types: Specify parameters and return types
  • Optional properties: Use ? for optional fields

In our project:

  • All files use .tsx extension (TypeScript + JSX)
  • Props interfaces define component contracts
  • Strict mode enabled for maximum safety

What you need to know:

  • Basic types
  • How to define interfaces
  • How to read type errors

That's enough to get started! The rest you'll learn by doing.

Next Up

Now let's learn about React, the UI library we use:

What is React? →