TypeScript, modern web geliştirmede vazgeçilmez bir araç haline geldi. Bu yazıda, TypeScript'in neden bu kadar önemli olduğunu ve nasıl etkili kullanılacağını detaylıca inceleyeceğiz.
TypeScript Nedir ve Neden Kullanmalıyız?
Temel Avantajlar
1. Type Safety
2. Kod Kalitesi
3. Developer Experience
İstatistikler
TypeScript Fundamentals
1. Basic Types ve Interfaces
`typescript
// Primitive types
let username: string = "Erdenay";
let age: number = 25;
let isActive: boolean = true;
// Arrays
let tags: string[] = ["web", "design", "seo"];
let scores: Array
// Tuples
let user: [string, number, boolean] = ["Erdenay", 25, true];
// Enums
enum UserRole {
Admin = "ADMIN",
User = "USER",
Guest = "GUEST"
}
// Interfaces
interface Product {
id: string;
name: string;
price: number;
inStock: boolean;
category?: string; // Optional
readonly createdAt: Date; // Readonly
}
// Type aliases
type ID = string | number;
type Status = "pending" | "approved" | "rejected";
// Union types
function printId(id: string | number) {
if (typeof id === "string") {
console.log(id.toUpperCase());
} else {
console.log(id.toFixed(2));
}
}
`
2. Advanced Types
`typescript
// Generics
function getFirstElement
return arr[0];
}
const firstNumber = getFirstElement([1, 2, 3]); // number
const firstString = getFirstElement(["a", "b"]); // string
// Utility Types
interface User {
id: string;
name: string;
email: string;
age: number;
}
// Partial - Makes all properties optional
type PartialUser = Partial
// Pick - Select specific properties
type UserPreview = Pick
// Omit - Exclude specific properties
type UserWithoutEmail = Omit
// Record - Create object type with specific keys
type UserRoles = Record
// Mapped Types
type ReadonlyUser = {
readonly [K in keyof User]: User[K];
};
// Conditional Types
type IsString
type Test1 = IsString
type Test2 = IsString
`
3. Function Types
`typescript
// Function type annotations
function add(a: number, b: number): number {
return a + b;
}
// Arrow function with types
const multiply = (a: number, b: number): number => a * b;
// Optional and default parameters
function greet(name: string, greeting: string = "Hello"): string {
return ${greeting}, ${name}!;
}
// Rest parameters
function sum(...numbers: number[]): number {
return numbers.reduce((acc, num) => acc + num, 0);
}
// Function overloads
function parseValue(value: string): string[];
function parseValue(value: number): number[];
function parseValue(value: string | number): string[] | number[] {
if (typeof value === "string") {
return value.split(",");
}
return [value];
}
`
React ile TypeScript Best Practices
1. Component Types
`tsx
import { FC, ReactNode } from 'react';
// Props interface
interface ButtonProps {
children: ReactNode;
onClick: () => void;
variant?: "primary" | "secondary";
disabled?: boolean;
}
// Functional Component with types
const Button: FC
children,
onClick,
variant = "primary",
disabled = false
}) => {
return (
);
};
// Generic component
interface ListProps
items: T[];
renderItem: (item: T) => ReactNode;
}
function List
return (
- {renderItem(item)}
{items.map((item, index) => (
))}
);
}
`
2. Hooks with TypeScript
`tsx
import { useState, useEffect, useCallback, useMemo } from 'react';
// useState with explicit type
const [user, setUser] = useState
const [count, setCount] = useState
// useEffect
useEffect(() => {
const fetchUser = async () => {
const response = await fetch('/api/user');
const data: User = await response.json();
setUser(data);
};
fetchUser();
}, []);
// useCallback
const handleClick = useCallback((id: string) => {
console.log(Clicked: ${id});
}, []);
// useMemo
const expensiveValue = useMemo(() => {
return computeExpensiveValue(items);
}, [items]);
// Custom hook with types
function useLocalStorage
const [value, setValue] = useState
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue] as const;
}
`
3. Event Handlers
`tsx
import { ChangeEvent, FormEvent, MouseEvent } from 'react';
function Form() {
const handleSubmit = (e: FormEvent
e.preventDefault();
// Handle form submission
};
const handleChange = (e: ChangeEvent
console.log(e.target.value);
};
const handleClick = (e: MouseEvent
console.log("Button clicked");
};
return (
);
}
`
Next.js ile TypeScript
1. Page Components
`tsx
// app/products/[id]/page.tsx
import type { Metadata } from 'next';
interface PageProps {
params: {
id: string;
};
searchParams: {
[key: string]: string | string[] | undefined;
};
}
export async function generateMetadata({ params }: PageProps): Promise
const product = await fetchProduct(params.id);
return {
title: product.name,
description: product.description,
};
}
export default async function ProductPage({ params, searchParams }: PageProps) {
const product = await fetchProduct(params.id);
return
}
`
2. API Routes
`ts
// app/api/products/route.ts
import { NextRequest, NextResponse } from 'next/server';
interface Product {
id: string;
name: string;
price: number;
}
export async function GET(request: NextRequest) {
const products: Product[] = await fetchProducts();
return NextResponse.json(products);
}
export async function POST(request: NextRequest) {
const body: Partial
const newProduct = await createProduct(body);
return NextResponse.json(newProduct, { status: 201 });
}
`
Enterprise Patterns
1. Domain-Driven Design
`typescript
// types/domain/product.ts
export interface ProductEntity {
id: ProductId;
name: ProductName;
price: Money;
stock: Stock;
}
export type ProductId = string & { readonly __brand: "ProductId" };
export type ProductName = string & { readonly __brand: "ProductName" };
export class Money {
private constructor(
public readonly amount: number,
public readonly currency: string
) {}
static create(amount: number, currency: string): Money {
if (amount < 0) throw new Error("Amount cannot be negative");
return new Money(amount, currency);
}
}
`
2. Repository Pattern
`typescript
interface Repository
findById(id: string): Promise
findAll(): Promise
create(entity: Omit
update(id: string, entity: Partial
delete(id: string): Promise
}
class ProductRepository implements Repository
async findById(id: string): Promise
// Implementation
}
// ... other methods
}
`
Performans ve Optimizasyon
1. Strict Mode Configuration
`json
// tsconfig.json
{
"compilerOptions": {
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"esModuleInterop": true,
"moduleResolution": "bundler",
"target": "ES2022",
"lib": ["ES2022", "DOM"],
"jsx": "preserve",
"incremental": true
}
}
`
2. Build Optimization
Compile Time:
Bundle Size:
Team Collaboration
1. Code Review Benefits
2. Documentation
`typescript
/
* Calculates the total price of items in cart
* @param items - Array of cart items
* @param discountCode - Optional discount code
* @returns Total price after discounts
* @throws {Error} If discount code is invalid
* @example
* `ts
* const total = calculateTotal(cartItems, "SUMMER25");
* `
*/
function calculateTotal(
items: CartItem[],
discountCode?: string
): number {
// Implementation
}
`
Enextware TypeScript Standartları
Tüm projelerimizde TypeScript kullanıyoruz:
Sonuçlar:
İletişim
TypeScript ile profesyonel web uygulamaları için:
Tel: +90 536 628 0007
E-posta: info@enextware.com
