Frontend

TypeScript 5.6: Decorators ve Yeni Type System

25 Aralık 20246 dk okuma
TypeScriptJavaScriptProgrammingType System

TypeScript 5.6: Decorators ve Yeni Type System


TypeScript 5.6, ECMAScript standartlarına tam uyumlu decorator desteği ve gelişmiş tip sistemi ile geldi. Bu yazıda, yeni özelliklerini ve nasıl kullanılacağını inceleyeceğiz.


ECMAScript Decorators


Artık standard decorator syntax'ı destekleniyor:


// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "experimentalDecorators": false, // Artık gerekli değil
    "decorators": true
  }
}

Class Decorators


function Logger(target: any) {
  return class extends target {
    constructor(...args: any[]) {
      console.log('Creating instance...');
      super(...args);
    }
  };
}

@Logger
class User {
  constructor(public name: string) {}
}

const user = new User('John'); // Logs: Creating instance...

Method Decorators


function Deprecated(target: any, key: string, descriptor: PropertyDescriptor) {
  const original = descriptor.value;
  
  descriptor.value = function(...args: any[]) {
    console.warn(`Method ${key} is deprecated`);
    return original.apply(this, args);
  };
  
  return descriptor;
}

class API {
  @Deprecated
  oldMethod() {
    return 'old';
  }
  
  newMethod() {
    return 'new';
  }
}

Property Decorators


function Readonly(target: any, key: string) {
  Object.defineProperty(target, key, {
    writable: false,
    configurable: false,
  });
}

class Product {
  @Readonly
  id: number = 1;
  
  name: string = 'Product';
}

const product = new Product();
product.id = 2; // Error: Cannot assign to read-only property

Yeni Type System Özellikleri


1. Improved Inference


// Daha iyi tip çıkarımı
function process<T>(items: T[]) {
  return items.map(item => ({
    ...item,
    processed: true,
  }));
}

const users = [{ id: 1, name: 'John' }];
const processed = process(users);
// Tip: { id: number; name: string; processed: boolean }[]

2. Template Literal Types


type EventName<T extends string> = `on${Capitalize<T>}`;

type ClickEvent = EventName<'click'>; // 'onClick'
type SubmitEvent = EventName<'submit'>; // 'onSubmit'

function addEventListener<T extends string>(
  event: T,
  handler: () => void
): void {
  // ...
}

addEventListener('click', () => {}); // ✅
addEventListener('onClick', () => {}); // ❌ Error

3. Const Assertions


const config = {
  api: 'https://api.example.com',
  timeout: 5000,
} as const;

// Tip: { readonly api: "https://api.example.com"; readonly timeout: 5000 }

Pratik Kullanım Örnekleri


1. Validation Decorator


function ValidateEmail(target: any, key: string) {
  let value: string;
  
  Object.defineProperty(target, key, {
    get: () => value,
    set: (newValue: string) => {
      if (!newValue.includes('@')) {
        throw new Error('Invalid email');
      }
      value = newValue;
    },
  });
}

class User {
  @ValidateEmail
  email: string = '';
}

2. Timing Decorator


function Timing(target: any, key: string, descriptor: PropertyDescriptor) {
  const original = descriptor.value;
  
  descriptor.value = async function(...args: any[]) {
    const start = performance.now();
    const result = await original.apply(this, args);
    const end = performance.now();
    console.log(`${key} took ${end - start}ms`);
    return result;
  };
  
  return descriptor;
}

class Service {
  @Timing
  async fetchData() {
    await new Promise(resolve => setTimeout(resolve, 1000));
    return { data: 'result' };
  }
}

Migration Rehberi


Eski Decorator Syntax'tan Yeniye


**Eski:**

// experimentalDecorators: true
class MyClass {
  @experimentalDecorator
  method() {}
}

**Yeni:**

// decorators: true
class MyClass {
  @standardDecorator
  method() {}
}

Sonuç


TypeScript 5.6, decorator desteği ve gelişmiş tip sistemi ile JavaScript geliştirmeyi daha güçlü hale getiriyor. ECMAScript standartlarına uyum, gelecekteki uyumluluk için önemli. Projelerinizi güncellemeyi ve yeni özellikleri denemeyi öneririm.

C

Caner Dedeoğlu