microsoft / microsoft/TypeScript
`.then(onresolved)`'s return type should not be inferred from contextual type
まだ誰も着手していません。
- 主要言語
- Go
- スター
- 111k
- フォーク
- 14.3k
- 平均マージ
- 1日 19時間
- マージ済み PR(30日)
- 117
説明
lib Update Request
Configuration Check
My compilation target is ES2015 and my lib is the default.
Also reproducible with target ESNext, ES2022 ect.
Missing / Incorrect Definition
Promise.prototype.then
Sample Code
TypeScript infers the return type of then from the contextual type information when called with only one argument.
This can cause unexpected results
let a: string | undefined
const b = a ?? await somePromise.then(() => "str")
I expect b to be string because either a is a string, somePromise resolves and then returns a string, or somePromise rejects and await throws so b is not assigned.
However b is actually string | undefined because the contextual type on the RHS of a nullish operator is the type of the LHS
and then inferred it's return type from the context because TResult2 was not inferred from arguments.
b satisfies string | undefined
I think there's actually two issues here
- The contextual type of the RHS of nullish operator is the type of the LHS
- .then's type definition does not use overloads for different number of arguments
The first issue seems debatable, I can understand the current behavior but these alternates make sense as well
- The contextual type of R should be
unknownor the same as the wholeL ?? Rexpression - The contextual type of R should be
NonNullable<L>
Let me know if this should be a separate issue or if there is interesting reading on the current behavior.
The next issue is caused because the return type of .then is Promise<TResult1 | TResult2> and TResult2 is not inferred from then's arguments when onrejected is not provided so it's inferred from the contextual type.
I think this issue can be fixed by changing the library to use overrides
then<TResult1>(onresolved: (t: T) => TResult1): Promise<TResult1>
then<TResult1, TResult2>(onresolved: (t: T) => TResult1, onrejected: (err: any) => TResult2): Promise<TResult1 | TResult2>
// more overrides for 0 or only onrejected args.
Documentation Link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
https://github.com/microsoft/TypeScript/blob/main/src/lib/es5.d.ts#L1524
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
src/lib/es5.d.ts の 1524 行付近にある Promise.prototype.then の定義から始め、提供された playground の例を再現してください。1 引数形式と 2 引数形式がどのように型付けされるかを確認し、nullish-operator のコンテキスト型付けに関する懸念を別途扱うべきか判断してください。1 引数形式の意図された型が、文書化されている Promise の動作を後退させることなく検証できれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- javascript, typescript
- 領域
- compilers
- issue の種類
- バグ
- 難易度
- 3/5
- 見積もり時間
- 1〜2日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100