Angular’da TypeScript Rehberi: Fonksiyonlar, Class, Array ve RxJS Observable (Detaylı Anlatım)
Angular öğrenmeye başlayanların en sık zorlandığı konu aslında Angular değil, TypeScript ve modern JavaScript temelleridir. Çünkü Angular; component, service, dependency injection ve reactive yapılarında TypeScript’i yoğun şekilde kullanır.
İçindekiler
- TypeScript Nedir ve Angular’daki Rolü
- Değişkenler ve Tip Anotasyonu
- Fonksiyon Tanımlama
- Opsiyonel & Rest Parametre
- Callback ve Arrow Function
- Array Yapısı
- Array Metotları (map / filter / reduce)
- Object Type Annotation
- Class Yapısı ve Inheritance
- Module Import / Export
- RxJS Observable Nedir?
1) TypeScript Nedir ve Angular’daki Rolü
TypeScript, JavaScript’in tip güvenli (type-safe) versiyonudur. Angular framework tamamen TypeScript üzerine inşa edilmiştir.
Angular’da component, service ve model yapıları class tabanlıdır ve tip güvenliği sayesinde daha az hata üretir.
2) Değişkenler ve Type Annotation
let city: string = "London";
let price: number = 100;
let isActive: boolean = true;
Tip anotasyonu Angular template hatalarını azaltır ve IDE desteğini güçlendirir.
3) TypeScript Fonksiyon Tanımlama
function writeValue(val: string | null): void {
console.log(val ?? "Default");
}
Angular servis metotları ve event handler’lar bu mantıkla yazılır.
4) Opsiyonel Parametre ve Rest Parametre
function logMessage(message?: string) {
console.log(message ?? "No message");
}
function writeValue(val: string, ...extras: string[]) {
console.log(val, extras);
}
5) Callback ve Arrow Function
function execute(fn: () => string) {
console.log(fn());
}
execute(() => "Hello Angular");
RxJS pipeline ve event handling bu yapıya dayanır.
6) Array Yapısı ve Angular’da Kullanımı
let users: string[] = ["Adam", "Eve"];
Angular’da *ngFor ile listeler doğrudan array üzerinden yönetilir.
7) Array Metotları: map / filter / reduce
const total = numbers
.filter(n => n > 0)
.reduce((sum, n) => sum + n, 0);
Angular uygulamalarında veri işleme için for-loop yerine bu yöntem tercih edilir.
8) Object Literals ve Optional Property
function printProduct(product: {
name: string;
price: number;
category?: string;
}) {
console.log(product.name);
}
9) Class Yapısı ve Inheritance
class Product {
constructor(public name: string, public price: number) {}
}
class DiscountProduct extends Product {
constructor(name: string, price: number, private discount: number) {
super(name, price - discount);
}
}
10) Module Import / Export
export class User {}
import { User } from './user.model';
Angular modüler mimari üzerine kuruludur.
11) RxJS Observable Nedir?
this.http.get('/api/users')
.subscribe(users => console.log(users));
Angular HttpClient her zaman Observable döner.
Özet
- TypeScript tip sistemi
- Fonksiyon ve parametre yapıları
- Array ve functional metotlar
- Class ve inheritance
- Module sistemi
- RxJS reactive mantık
Angular’da profesyonel ve sürdürülebilir projeler geliştirmek için bu temelleri sağlam öğrenmek kritik öneme sahiptir.