🔍

TypeScriptのPromiseLikeについて知ろう

に公開

概要

別記事を書くにあたりPromiseLikeを理解しようの会

PromiseLikeとは

Promiseのcatchメソッドがない版
ここで記載されている定義によると

interface PromiseLike<T> {
    /**
     * Attaches callbacks for the resolution and/or rejection of the Promise.
     * @param onfulfilled The callback to execute when the Promise is resolved.
     * @param onrejected The callback to execute when the Promise is rejected.
     * @returns A Promise for the completion of which ever callback is executed.
     */
    then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
}

となっており、Promise

interface Promise<T> {
    /**
     * Attaches callbacks for the resolution and/or rejection of the Promise.
     * @param onfulfilled The callback to execute when the Promise is resolved.
     * @param onrejected The callback to execute when the Promise is rejected.
     * @returns A Promise for the completion of which ever callback is executed.
     */
    then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;

    /**
     * Attaches a callback for only the rejection of the Promise.
     * @param onrejected The callback to execute when the Promise is rejected.
     * @returns A Promise for the completion of the callback.
     */
    catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
}

と記載されている。
なので以下のような差分があるイメージ。

// Promiseで定義
const myPromise: Promise<string> = new Promise<string>((resolve) => {
  const success = true;
  if (success) {
    resolve("処理成功");
  }
});

// PromiseLikeで定義
const myPromiseLike: PromiseLike<string> = new Promise<string>(
  (resolve, reject) => {
    const success = true;
    if (success) {
      resolve("処理成功");
    } else {
      reject;
    }
  }
);

// ✅ Promiseで定義しているので.then()も.catch()も使えるのでOK
myPromise
  .then((data) => {
    console.log("成功:", data);
  })
  .catch((error) => {
    console.log("失敗:", error);
  });

// 🚫 PromiseLikeで定義しているので.catch()が使えずNG
myPromiseLike
  .then((data) => {
    console.log("成功:", data);
  })
  .catch((error) => {
    console.log("失敗:", error);
  });

Discussion