TypeScript Best Practices: Tip Güvenli Kod Yazma Sanatı
TypeScript, JavaScript ekosisteminde tip güvenliği sağlayan güçlü bir araç. Bu yazıda en iyi pratikleri paylaşacağım.
🔒 Strict Mode Kullanın
// tsconfig.json
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true
}
}
🎯 Type yerine Interface Kullanın
// ✅ İYEL
interface User {
id: number
name: string
email: string
}
// ❌ KÖTÜ
type User = {
id: number
name: string
email: string
}
🔄 Generics Kullanımı
function fetchData(url: string): Promise {
return fetch(url).then(res => res.json())
}
interface Post {
id: number
title: string
}
const post = await fetch('/api/posts/1')
🛡️ Type Guards
function isString(value: unknown): value is string {
return typeof value === 'string'
}
function processValue(value: unknown) {
if (isString(value)) {
console.log(value.toUpperCase())
}
}
📝 Utility Types
interface User {
id: number
name: string
email: string
}
// Partial - tüm özellikler optional
type PartialUser = Partial
// Required - tüm özellikler required
type RequiredUser = Required
// Pick - sadece belirli özellikler
type UserSummary = Pick
Sonuç
TypeScript doğru kullanıldığında daha güvenli ve sürdürülebilir kod yazmanızı sağlar.
