Geri

TypeScript ReturnType Utility Type

`ReturnType< T >`, verilen fonksiyon tipinin dönüş değerinin türünü çıkarır ve kullanmanızı sağlar.

Temel Örnek

function getUser() {
    return { id: 1, name: "Alice", age: 30 };
  }
  
  type User = ReturnType<typeof getUser>;
  
  const user1: User = { id: 2, name: "Bob", age: 25 };
  // const user2: User = { id: 3, name: "Charlie" }; // Error: age not assigned

Bir fonksiyonun dönüş tipini otomatik olarak yakalayıp, başka tip tanımlarında kullanabilirsiniz.

Fonksiyon Dönüş Tipini Tip Güvenliği İçin Kullanma

function calculateTotal(price: number, quantity: number) {
    return price * quantity;
  }
  
  type Total = ReturnType<typeof calculateTotal>;
  
  const totalAmount: Total = 100;
  // const wrongTotal: Total = "100"; // Error: cannot be string

Fonksiyon dönüş tipi ile uyumsuz veri atamaları derleme hatası verir.

Async Fonksiyonlarda Kullanımı

type AsyncFunction = () => Promise<string>;
  
  type ResultType = ReturnType<AsyncFunction>;
  // ResultType = Promise<string>
  
  async function asyncFunc(): Promise<string> {
    return "hello";
  }
  
  asyncFunc().then(result => {
    console.log(result); // "hello"
  });

Promise dönen fonksiyonların dönüş tipi `Promise< T >` olarak yakalanır ve bu tip üzerinden işlem yapılabilir.

Neden Kullanılır?

`ReturnType`, fonksiyon dönüş tipini manuel yazmak yerine otomatik çıkararak tip tutarlılığı ve bakımı kolaylaştırır.

Geri