TypeScript Tutorial: Upgrade Your JavaScript

TELEGRAM
0/5 Votos: 0
Reportar esta app

Descripción

Why TypeScript Is Worth the Effort

I resisted TypeScript for years. “JavaScript is fine,” I thought. Then I inherited a large codebase with zero types. Debugging mysterious undefined errors at 2am changed my mind permanently.

TypeScript in 5 Minutes

// JavaScript - what does this function expect?
function processUser(user) {
    return user.name.toUpperCase();
}

// TypeScript - crystal clear
interface User {
    id: number;
    name: string;
    email: string;
    role: 'admin' | 'user' | 'guest';
}

function processUser(user: User): string {
    return user.name.toUpperCase();
}

// TypeScript catches this at compile time:
processUser({ id: 1, name: "Alice" }); // Error! Missing email and role

Essential TypeScript Features

Types and Interfaces

// Primitive types
const name: string = "Alice";
const age: number = 30;
const active: boolean = true;

// Arrays
const scores: number[] = [90, 85, 92];
const names: Array<string> = ["Alice", "Bob"];

// Interface
interface ApiResponse<T> {
    data: T;
    status: number;
    message: string;
}

// Usage
const response: ApiResponse<User[]> = {
    data: users,
    status: 200,
    message: "Success"
};

Generics

function getFirst<T>(arr: T[]): T | undefined {
    return arr[0];
}

const firstNumber = getFirst([1, 2, 3]);   // type: number
const firstName = getFirst(["a", "b"]);    // type: string

Migrating from JavaScript

  1. Rename .js files to .ts one at a time
  2. Set "strict": false initially
  3. Fix errors gradually, starting with any types
  4. Enable strict mode once codebase is stable

tsconfig.json Essentials

{
    "compilerOptions": {
        "target": "ES2022",
        "module": "commonjs",
        "strict": true,
        "outDir": "./dist",
        "rootDir": "./src"
    }
}

Deixe um comentário

O seu endereço de email não será publicado. Campos obrigatórios marcados com *