0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TypeScriptでPromise.then()のコールバック関数の型を取る

Posted at

タイトルの通りです。特に補足はありません。
Promiseに指定した型を、二重指定したくなくて作りました。

type KeyType<T, K extends keyof T> = T[K];
export type FullFilledParams<PROMISE extends Promise<any>> = KeyType<Parameters<Extract<KeyType<Parameters<KeyType<Pick<PROMISE, 'then'>, 'then'>>, 0>, Function>>, 0>;
export type RejectedParams<PROMISE extends Promise<any>> = KeyType<Parameters<Extract<KeyType<Parameters<KeyType<Pick<PROMISE, 'then'>, 'then'>>, 1>, Function>>, 0>;

// 使い方
const promise = new Promise<number>((r) => r(0));
type F = FullFilledParams<typeof promise>;
type R = RejectedParams<typeof promise>;
promise.then((v: F) => { }, (e: R) => { });
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?