TypeScript, modern JavaScript geliştirmede vazgeçilmez bir araç haline geldi. Bu makalede, TypeScript ile type-safe kod yazmanın en iyi yollarını keşfedeceğiz.
TypeScript'in Avantajları
1. Erken Hata Tespiti
TypeScript, compile-time'da hataları yakalar. Bu, runtime hatalarını önler ve geliştirme sürecini hızlandırır.
2. Daha İyi IDE Desteği
TypeScript ile IDE'ler daha iyi autocomplete ve refactoring desteği sunar.
3. Kod Dokümantasyonu
Tipler, kodun kendisini dokümante eder ve yeni geliştiricilerin projeyi anlamasını kolaylaştırır.
Type Definitions
Interface vs Type
// Interface - genişletilebilir
interface User {
id: string;
name: string;
}
interface Admin extends User {
role: 'admin';
}
// Type - union ve intersection için daha uygun
type Status = 'pending' | 'approved' | 'rejected';
type UserWithStatus = User & { status: Status };
Generic Types
Generic'ler, yeniden kullanılabilir ve type-safe kod yazmanızı sağlar:
function getValue<T>(key: string): T | null {
const value = localStorage.getItem(key);
return value ? JSON.parse(value) : null;
}
const user = getValue<User>('user'); // Type: User | null
Utility Types
TypeScript'in built-in utility type'ları:
interface User {
id: string;
name: string;
email: string;
age: number;
}
// Partial - tüm property'leri optional yapar
type PartialUser = Partial<User>;
// Pick - belirli property'leri seçer
type UserPreview = Pick<User, 'id' | 'name'>;
// Omit - belirli property'leri çıkarır
type UserWithoutEmail = Omit<User, 'email'>;
// Record - key-value mapping
type UserMap = Record<string, User>;
Type Guards
Type guard'lar, runtime'da tip kontrolü yapmanızı sağlar:
function isUser(obj: unknown): obj is User {
return (
typeof obj === 'object' &&
obj !== null &&
'id' in obj &&
'name' in obj &&
'email' in obj
);
}
function processUser(data: unknown) {
if (isUser(data)) {
// TypeScript artık data'nın User olduğunu biliyor
console.log(data.name);
}
}
Strict Mode
tsconfig.json'da strict mode'u aktif edin:
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true
}
}
Best Practices
1. Explicit Return Types
Fonksiyonlarda explicit return type kullanın:
function calculateTotal(items: Item[]): number {
return items.reduce((sum, item) => sum + item.price, 0);
}
2. Avoid Any
any kullanmaktan kaçının. Bunun yerine unknown kullanın:
function processData(data: unknown) {
if (typeof data === 'string') {
// Type guard ile tip kontrolü
console.log(data.toUpperCase());
}
}
3. Use Const Assertions
Const assertion'lar ile daha spesifik tipler oluşturun:
const colors = ['red', 'green', 'blue'] as const;
type Color = typeof colors[number]; // 'red' | 'green' | 'blue'
Sonuç
TypeScript, daha güvenli ve bakımı kolay kod yazmanızı sağlar. Bu best practice'leri uygulayarak, type-safe ve ölçeklenebilir uygulamalar geliştirebilirsiniz.