microsoft / microsoft/TypeScript

Inferred type parameter does not satisfy constraint

オープン
#45,286 コメント 0 件 リアクション 6 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

Bug Domain: check: Type Inference
主要言語
Go
スター
111k
フォーク
14.4k
平均マージ
1日 19時間
マージ済み PR(30日)
117

説明

Bug Report

🔎 Search Terms

generic constraint, inference, invalid, specified, manually, explicitly, invalid

🕗 Version & Regression Information
  • This changed between versions 3.3 and 3.5
⏯ Playground Link

Playground link with relevant code

💻 Code
declare function f<T, U extends T>(cb: (u: U) => T): U

const v = f(u => "x");
// const v: unknown <-- wait, what?
// function f<string, unknown>(cb: (u: unknown) => string): unknown

f<string, unknown>(u => "x"); // error, of course
// -----> ~~~~~~~
// Type 'unknown' does not satisfy the constraint 'string'.
🙁 Actual behavior

In TS3.5+, the type parameter T is inferred to be string, and U is inferred to be unknown in the first call to f(). But then U extends T is not met; you couldn't even manually specify T and U like this when calling f(), as shown in the second call to f().

(In TS3.3, T and U are both inferred as {}.)

🙂 Expected behavior

Either I'd expect both T and U to be string, or I'd expect an error where the compiler says it cannot find a suitable candidate for U. Presumably the compiler has not inferred T before it needs to infer U, and so it constrains U to T's constraint which is implicitly unknown, and then falls back to that. But it never circles back to make sure that such a fallback actually works for U extends T.


I came upon this while looking for an answer to this SO question. This behavior is weird, right? I haven't found an existing issue for it.

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

リンクされた TypeScript Playground の例を再現し、報告された動作を TypeScript 3.3 および 3.5+ と比較します。まず、示されている関数呼び出しについて、ジェネリック型の推論と制約チェックを追跡します。コンパイラが推論された U extends T 制約を一貫して処理し、選択した期待される動作に対するリグレッションカバレッジが用意されていれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
typescript
領域
compilers
issue の種類
バグ
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
32/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。