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
- Type Safety
- Better IDE Support
- Improved Code Quality
- 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
- Folosește strict mode
- Definește interfețe pentru API responses
- Utilizează type guards
- Evită any când este posibil
- 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.