職質アンチパターン

無責任な事を書きたい

TypeScriptのasync functionに戻り値の型を明記すると,Promiseの型パラメータの推論が効かなくなる (場合がある)

前提.

$ $(yarn bin)/tsc --version
Version 2.8.3

async を付けない場合,以下のコードはコンパイルが通る.

function foo(): Promise<string> {
  return new Promise((resolve) => resolve('foo'));
}

async を付与すると上記コードはコンパイルが通らなくなる.

// NG!
async function foo(): Promise<string> {
  return new Promise((resolve) => resolve('foo'));
}

以下のように,戻り値側にも型パラメータを付与するとコンパイルが通る.

async function foo(): Promise<string> {
  return new Promise<string>((resolve) => resolve('foo'));
}

これは Promise を明示的にreturnしている場合にこういう状況になるのであって,以下のように暗黙的なPromiseを返却する時は問題がない.

async function foo(): Promise<string> {
  return 'foo';
}

なぜなんだろう? ふつうにasyncの場合でも推論が効いて欲しい気がする?

--

コンパイルエラーメッセージは以下の通り.

src/example.ts(2,3): error TS2322: Type '{}' is not assignable to type 'string'.

[追記]

GitHubにissueが上がっていた.

github.com

Looks like a linter issue.
if a function is marked as async, the compiler will wrap the return value with a new Promise.
https://github.com/Microsoft/TypeScript/issues/23114#issuecomment-378360613

なるほど……しかし自動closeされちゃっている……