Introduction to TypeScript & Setup
What is TypeScript?
TypeScript is a strongly typed superset of JavaScript that compiles to plain JavaScript. It adds optional static typing, classes, interfaces, and modern features while maintaining full compatibility with existing JavaScript code.
Why TypeScript?
- Catches errors at compile time
- Excellent tooling and IntelliSense
- Scales beautifully for large applications
- Industry standard for modern web development (React, Angular, Node.js)
Installation & Setup
npm install -g typescript tsc --version
Your First TypeScript Program
function greet(name: string): string { return `Hello, ${name}! Welcome to TypeScript Mastery.`; } console.log(greet("Tinashe"));
Install TypeScript globally, create a new file intro.ts, add type annotations, compile it with tsc intro.ts, and run the generated JavaScript.
Variables & Data Types
Core Types
let age: number = 30; let name: string = "Alice"; let isDone: boolean = false; let list: number[] = [1, 2, 3];
The 'any' and 'unknown' Types
Use unknown for values where you don't know the type yet; it's safer than any.
Functions & Interfaces
Interfaces
Interfaces define the "shape" of an object.
interface User { id: number; username: string; email?: string; // Optional } const user: User = { id: 1, username: "dev_01" };
Control Flow & Arrays
Tuples
Tuples allow you to express an array with a fixed number of elements whose types are known.
let x: [string, number]; x = ["hello", 10]; // OK
Objects & Classes
Class Access Modifiers
class Animal { public name: string; private age: number; constructor(name: string) { this.name = name; } }
Generics
Reusable Types
function identity<T>(arg: T): T { return arg; } let output = identity<string>("myString");
Modules & Namespaces
Export & Import
// math.ts export const PI = 3.14; // main.ts import { PI } from "./math";
Type Guards & Assertions
Type Checking at Runtime
function isString(x: any): x is string { return typeof x === "string"; }
Advanced Types
Utility Types
Partial<T>: All properties optionalReadonly<T>: All properties readonlyPick<T, K>: Select subset of properties
DOM Manipulation
Using TypeScript to safely interact with the browser's DOM API.
const btn = document.getElementById("myBtn") as HTMLButtonElement; btn.addEventListener("click", () => console.log("Clicked!"));
React with TypeScript
Typing Props & State
interface Props { title: string; } const MyComp: React.FC<Props> = ({ title }) => <h1>{title}</h1>;
Capstone Project: Weather App
Build a weather dashboard using TypeScript, fetching data from a REST API and displaying it with full type safety.
// Project requirements: // 1. Define interfaces for API responses // 2. Use async/await with fetch // 3. Handle loading and error states // 4. Use Generics for API wrapper functions