LoginSignup
0
0

TypeScriptでの非同期処理 戻り値の型どうする? Promise<T>

Posted at

TypeScriptと非同期処理

JavaScriptのスーパーセットであるTypeScriptは、静的型付けを採用しており、より安全で保守性の高いコードを記述することが可能な言語。

非同期関数にはどのような型注釈をするべきか

通常、非同期関数の戻り値はPromise型を指定する。ここでTはPromiseが解決された時の値の型を表す。

// 誤った型注釈
const getString = async(): string => {
    return "hello world";
};

// 正しい型注釈
const getString = async(): Promise<string> => {
    return "hello world";
};

awaitを使用して非同期関数の戻り値を取得する場合は、その戻り値はPromiseが解決された結果の型、つまりTとなる。

// 誤った型注釈
const str: Promise<string> = await getString();

// 正しい型注釈
const str: string = await getString();

▼参考文献

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