
TypeScript Temel Rehberi: JavaScript'e Tip Güvenliği Ekleme
TypeScript Temel Rehberi: JavaScript'e Tip Güvenliği Ekleme
TypeScript, Microsoft tarafından geliştirilen ve JavaScript'e statik tip kontrolü ekleyen güçlü bir programlama dilidir. Bu rehberde, TypeScript'in temellerini öğrenecek ve modern web uygulamaları geliştirmek için nasıl kullanacağınızı göreceksiniz.
TypeScript Nedir?
TypeScript, JavaScript'in üzerine inşa edilmiş bir dil olup, geliştirme zamanında tip kontrolü sağlar. JavaScript'e dönüştürülür ve tüm JavaScript özelliklerini destekler.
TypeScript'in Avantajları
- Erken hata tespiti - Derleme zamanında hataları yakalar
- Daha iyi IDE desteği - Otomatik tamamlama ve refactoring
- Daha iyi kod dokümantasyonu - Tipler kodun kendisini dokümante eder
- Daha güvenli refactoring - Tip sistemi sayesinde güvenli değişiklikler
- Daha iyi takım çalışması - Kod daha anlaşılır ve maintainable
Temel Tip Tanımları
1. Primitive Tipler
// String
let name: string = "Ahmet";
let message: string = `Merhaba ${name}!`;
// Number
let age: number = 25;
let price: number = 99.99;
let binary: number = 0b1010; // Binary
let hex: number = 0xf00d; // Hexadecimal
// Boolean
let isActive: boolean = true;
let isCompleted: boolean = false;
// Null ve Undefined
let nullValue: null = null;
let undefinedValue: undefined = undefined;
// Symbol
let symbol: symbol = Symbol("unique");
// BigInt
let bigNumber: bigint = 100n;
2. Array ve Tuple
// Array
let numbers: number[] = [1, 2, 3, 4, 5];
let names: Array<string> = ["Ahmet", "Mehmet", "Ayşe"];
// Tuple - Sabit uzunluklu array
let person: [string, number, boolean] = ["Ahmet", 25, true];
// Tuple kullanımı
function getUserInfo(): [string, number] {
return ["Ahmet", 25];
}
const [userName, userAge] = getUserInfo();
// Optional tuple elements
let optionalTuple: [string, number?] = ["Ahmet"]; // İkinci element opsiyonel
3. Object ve Interface
// Object tip tanımı
let user: {
name: string;
age: number;
email?: string; // Opsiyonel property
} = {
name: "Ahmet",
age: 25
};
// Interface tanımı
interface User {
id: number;
name: string;
email: string;
age?: number;
readonly createdAt: Date; // Sadece okunabilir
}
// Interface kullanımı
const user1: User = {
id: 1,
name: "Ahmet",
email: "ahmet@example.com",
createdAt: new Date()
};
// Interface extension
interface Employee extends User {
department: string;
salary: number;
}
const employee: Employee = {
id: 1,
name: "Ahmet",
email: "ahmet@example.com",
department: "IT",
salary: 5000,
createdAt: new Date()
};
4. Function Tipleri
// Function tip tanımı
function add(a: number, b: number): number {
return a + b;
}
// Arrow function tip tanımı
const multiply: (a: number, b: number) => number = (a, b) => a * b;
// Function interface
interface MathFunc {
(a: number, b: number): number;
}
const divide: MathFunc = (a, b) => a / b;
// Optional ve default parametreler
function greet(name: string, greeting: string = "Merhaba"): string {
return `${greeting}, ${name}!`;
}
// Rest parametreler
function sum(...numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
// Function overloads
function processData(data: string): string;
function processData(data: number): number;
function processData(data: string | number): string | number {
if (typeof data === "string") {
return data.toUpperCase();
} else {
return data * 2;
}
}
Union ve Intersection Tipler
1. Union Types
// Union type - Birden fazla tip
let id: string | number = "abc123";
id = 123; // Geçerli
// Union type ile function
function processId(id: string | number): string {
if (typeof id === "string") {
return id.toUpperCase();
} else {
return id.toString();
}
}
// Union type ile array
let mixedArray: (string | number)[] = ["hello", 42, "world", 100];
// Literal union types
type Status = "pending" | "approved" | "rejected";
let orderStatus: Status = "pending";
2. Intersection Types
// Intersection type - Birden fazla tipin birleşimi
interface HasName {
name: string;
}
interface HasAge {
age: number;
}
type Person = HasName & HasAge;
const person: Person = {
name: "Ahmet",
age: 25
};
// Intersection ile function
type StringOrNumber = string | number;
type NumberOrBoolean = number | boolean;
type Combined = StringOrNumber & NumberOrBoolean; // number
Generic Types
1. Generic Functions
// Generic function
function identity<T>(arg: T): T {
return arg;
}
// Kullanım
let output1 = identity<string>("hello");
let output2 = identity(42); // Type inference
// Generic interface
interface Box<T> {
contents: T;
}
let stringBox: Box<string> = { contents: "hello" };
let numberBox: Box<number> = { contents: 42 };
// Generic class
class Container<T> {
private value: T;
constructor(value: T) {
this.value = value;
}
getValue(): T {
return this.value;
}
setValue(value: T): void {
this.value = value;
}
}
const stringContainer = new Container<string>("hello");
const numberContainer = new Container<number>(42);
2. Generic Constraints
// Generic constraint
interface Lengthwise {
length: number;
}
function logLength<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
// Kullanım
logLength("hello"); // string has length
logLength([1, 2, 3]); // array has length
// logLength(42); // Error: number doesn't have length
// Multiple constraints
interface HasName {
name: string;
}
interface HasAge {
age: number;
}
function processPerson<T extends HasName & HasAge>(person: T): T {
console.log(`${person.name} is ${person.age} years old`);
return person;
}
Advanced Types
1. Conditional Types
// Conditional type
type NonNullable<T> = T extends null | undefined ? never : T;
type T1 = NonNullable<string | number | null>; // string | number
type T2 = NonNullable<string[] | null | undefined>; // string[]
// Conditional type ile function
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
function getString(): string {
return "hello";
}
type StringReturn = ReturnType<typeof getString>; // string
2. Mapped Types
// Mapped type
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
type Partial<T> = {
[P in keyof T]?: T[P];
};
// Kullanım
interface User {
id: number;
name: string;
email: string;
}
type ReadonlyUser = Readonly<User>;
type PartialUser = Partial<User>;
// Mapped type ile modifier
type Required<T> = {
[P in keyof T]-?: T[P];
};
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
3. Utility Types
// Utility types
interface User {
id: number;
name: string;
email: string;
age?: number;
}
// Partial - Tüm property'leri opsiyonel yapar
type PartialUser = Partial<User>;
// Required - Tüm property'leri zorunlu yapar
type RequiredUser = Required<User>;
// Pick - Belirli property'leri seçer
type UserName = Pick<User, 'name'>;
// Omit - Belirli property'leri çıkarır
type UserWithoutId = Omit<User, 'id'>;
// Record - Key-value çiftleri için
type UserRoles = Record<string, string[]>;
// ReturnType - Function'ın return tipini alır
function getUser(): User {
return { id: 1, name: "Ahmet", email: "ahmet@example.com" };
}
type UserReturn = ReturnType<typeof getUser>;
// Parameters - Function'ın parametre tiplerini alır
function createUser(name: string, age: number): User {
return { id: 1, name, email: "", age };
}
type CreateUserParams = Parameters<typeof createUser>; // [string, number]
Type Guards ve Type Assertions
1. Type Guards
// typeof type guard
function processValue(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase();
} else {
return value.toString();
}
}
// instanceof type guard
class Dog {
bark() {
return "Woof!";
}
}
class Cat {
meow() {
return "Meow!";
}
}
function makeSound(animal: Dog | Cat): string {
if (animal instanceof Dog) {
return animal.bark();
} else {
return animal.meow();
}
}
// Custom type guard
interface User {
id: number;
name: string;
}
interface Admin {
id: number;
name: string;
permissions: string[];
}
function isAdmin(user: User | Admin): user is Admin {
return 'permissions' in user;
}
function processUser(user: User | Admin): string {
if (isAdmin(user)) {
return `Admin ${user.name} has permissions: ${user.permissions.join(', ')}`;
} else {
return `User ${user.name}`;
}
}
2. Type Assertions
// Type assertion
let someValue: unknown = "hello world";
let strLength: number = (someValue as string).length;
// Alternative syntax
let strLength2: number = (<string>someValue).length;
// Const assertions
const colors = ["red", "green", "blue"] as const;
type Color = typeof colors[number]; // "red" | "green" | "blue"
// Non-null assertion
function getElement(id: string): HTMLElement | null {
return document.getElementById(id);
}
const element = getElement("myId")!; // Non-null assertion
element.style.color = "red";
Namespaces ve Modules
1. Namespaces
// Namespace tanımı
namespace MathUtils {
export function add(a: number, b: number): number {
return a + b;
}
export function multiply(a: number, b: number): number {
return a * b;
}
export const PI = 3.14159;
}
// Namespace kullanımı
const result = MathUtils.add(5, 3);
const area = MathUtils.multiply(MathUtils.PI, 10);
// Nested namespace
namespace Geometry {
export namespace Circle {
export function area(radius: number): number {
return Math.PI * radius * radius;
}
}
export namespace Rectangle {
export function area(width: number, height: number): number {
return width * height;
}
}
}
2. ES6 Modules
// math.ts
export interface Point {
x: number;
y: number;
}
export function distance(p1: Point, p2: Point): number {
const dx = p2.x - p1.x;
const dy = p2.y - p1.y;
return Math.sqrt(dx * dx + dy * dy);
}
export const PI = 3.14159;
// Default export
export default class Calculator {
add(a: number, b: number): number {
return a + b;
}
}
// user.ts
import Calculator, { Point, distance, PI } from './math';
const p1: Point = { x: 0, y: 0 };
const p2: Point = { x: 3, y: 4 };
const dist = distance(p1, p2);
const calc = new Calculator();
const sum = calc.add(5, 3);
Decorators
// Class decorator
function log(target: any) {
console.log(`Class ${target.name} is being defined`);
}
@log
class Example {
// ...
}
// Method decorator
function logMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
console.log(`Calling ${propertyKey} with args:`, args);
const result = originalMethod.apply(this, args);
console.log(`Result:`, result);
return result;
};
return descriptor;
}
class Calculator {
@logMethod
add(a: number, b: number): number {
return a + b;
}
}
// Property decorator
function readonly(target: any, propertyKey: string) {
Object.defineProperty(target, propertyKey, {
writable: false
});
}
class User {
@readonly
id: number = 1;
}
TypeScript Configuration
1. tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"sourceMap": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"dist"
]
}
2. Strict Mode
// strict: true ile aktif olan özellikler
// noImplicitAny
function process(data) { // Error: Parameter 'data' implicitly has an 'any' type
return data.length;
}
// strictNullChecks
let name: string = null; // Error: Type 'null' is not assignable to type 'string'
// strictFunctionTypes
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
let f1 = (x: Animal) => void;
let f2 = (x: Dog) => void;
f1 = f2; // Error in strict mode
f2 = f1; // OK
Best Practices
1. Tip Tanımları
// ❌ Yanlış - any kullanımı
function processData(data: any): any {
return data;
}
// ✅ Doğru - Spesifik tipler
function processData<T>(data: T): T {
return data;
}
// ❌ Yanlış - Gereksiz tip tanımları
const name: string = "Ahmet";
const age: number = 25;
// ✅ Doğru - Type inference kullanımı
const name = "Ahmet";
const age = 25;
2. Interface vs Type
// Interface - Extend edilebilir
interface User {
name: string;
age: number;
}
interface Admin extends User {
permissions: string[];
}
// Type - Union ve intersection için
type Status = "pending" | "approved" | "rejected";
type UserOrAdmin = User | Admin;
3. Error Handling
// Result type pattern
type Result<T, E = Error> =
| { success: true; data: T }
| { success: false; error: E };
function divide(a: number, b: number): Result<number, string> {
if (b === 0) {
return { success: false, error: "Division by zero" };
}
return { success: true, data: a / b };
}
// Kullanım
const result = divide(10, 2);
if (result.success) {
console.log("Sonuç:", result.data);
} else {
console.error("Hata:", result.error);
}
Sonuç
TypeScript, JavaScript geliştirmeyi daha güvenli ve maintainable hale getiren güçlü bir araçtır. Bu rehberde öğrendiklerinizi pratik projelerde uygulayarak, tip güvenli web uygulamaları geliştirebilirsiniz.
Önemli Noktalar:
- TypeScript JavaScript'in üzerine inşa edilmiştir
- Tip sistemi geliştirme zamanında hataları yakalar
- Interface'ler ve type'lar kod dokümantasyonu sağlar
- Generic'ler yeniden kullanılabilir kod yazmanızı sağlar
- Strict mode ile daha güvenli kod yazın
Bu rehberde öğrendiklerinizi pratik projelerde uygulayarak, TypeScript becerilerinizi geliştirebilirsiniz.
İlgili Kaynaklar: