microsoft / microsoft/TypeScript

Type narrowing discards template type on this-typed return value

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

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

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

説明

Bug Report

🔎 Search Terms

type narrowing template constraint

🕗 Version & Regression Information

Bug occurs in every version on the playground

⏯ Playground Link

Playground link with relevant code

💻 Code
abstract class Foo {
  abstract clone(): this;
}

function cloneMe<T extends Foo|Date>(x: T): T {
  if (x instanceof Foo) return x.clone();
  // These casts are necessary because of https://github.com/microsoft/TypeScript/issues/38309.
  return new Date(x as Date) as T;
}
🙁 Actual behavior

Type 'Foo & Foo' is not assignable to type 'T'. 'Foo & Foo' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Foo | Date'.

🙂 Expected behavior

No errors; just like the instanceof check narrows x to Foo & T, the this return type of x.clone() should also be Foo & T rather than degrading to Foo & Foo.

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

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

はじめの一歩

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

調査の方向性

リンクされている TypeScript Playground の例から始め、cloneMe に関係する型の絞り込みとポリモーフィックな this の戻り値の挙動を調査してください。x.clone() の戻り値が Foo & T として保持され、キャストやエラーなしで例の型チェックが通れば、issue は完了です。

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

評価

技術スタック
typescript
領域
compilers
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
35/100

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

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