Sima Alexandru

Înapoi la blog

TypeScript în dezvoltarea web modernă

Sima Alexandru
TypeScript în dezvoltarea web modernă

TypeScript în dezvoltarea web modernă

Introducere

TypeScript a devenit un standard în dezvoltarea web modernă. În acest articol, vom explora cum TypeScript ne ajută să scriem cod mai sigur și mai ușor de întreținut.

Beneficiile TypeScript

  1. Type Safety
  2. Better IDE Support
  3. Improved Code Quality
  4. Better Documentation

Configurarea TypeScript

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

Exemple practice

Definirea interfețelor

interface User {
  id: string;
  name: string;
  email: string;
  role: "admin" | "user";
}

interface Post {
  id: string;
  title: string;
  content: string;
  author: User;
  createdAt: Date;
}

Generice

function getData<T>(url: string): Promise<T> {
  return fetch(url).then((res) => res.json());
}

// Utilizare
const user = await getData<User>("/api/user");
const posts = await getData<Post[]>("/api/posts");

Type Guards

function isUser(value: unknown): value is User {
  return (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    "name" in value &&
    "email" in value
  );
}

// Utilizare
const data = await fetch("/api/user");
if (isUser(data)) {
  console.log(data.name); // TypeScript știe că data este User
}

Best Practices

  1. Folosește strict mode
  2. Definește interfețe pentru API responses
  3. Utilizează type guards
  4. Evită any când este posibil
  5. Documentează tipurile complexe

Concluzie

TypeScript oferă un nivel suplimentar de siguranță și claritate în dezvoltarea web. Cu o configurare corectă și urmând best practices, poți scrie cod mai robust și mai ușor de întreținut.

Resurse utile

Tag-uri:

TypeScriptWeb DevelopmentProgrammingBest Practices