AI Bültenim Yapay Zeka Haber Portalı Logosu
Kod

Strict TypeScript tipleri

any temizliği ve ayrıştırılmış birlik tipleri.

Kod Prompt Kütüphanesi için temsili kategori görseli

Prompt Metni

Aşağıdaki TypeScript fonksiyonundaki any kullanımını kaldır. Başarı ve hata cevapları için discriminated union kullan; noUncheckedIndexedAccess açıkken güvenli çalışsın.

function firstMessage(response: any) {
  return response.messages[0].text
}

Fonksiyonun güvenli son halini ve iki kullanım örneğini göster.

Prompt Sonucu

type Message = { id: string text: string } type ApiResponse = | { ok: true; messages: Message[] } | { ok: false; error: string } function firstMessage(response: ApiResponse): string { if (!response.ok) { return response.error } const first = response.messages[0] return first?.text ?? 'Mesaj bulunamadı.' } const success: ApiResponse = { ok: true, messages: [{ id: '1', text: 'Merhaba' }], } const failure: ApiResponse = { ok: false, error: 'Servise ulaşılamadı.', } firstMessage(success) // Merhaba firstMessage(failure) // Servise ulaşılamadı. ok alanı union tipini daraltır. İlk eleman undefined olabileceği için optional chaining ve varsayılan değer kullanılır.

AI Bültenim prompt kütüphanesi — Tüm promptlar