microsoft / microsoft/TypeScript
Type narrowing in loose equality fails for edge cases like empty string and zero
まだ誰も着手していません。
- 主要言語
- Go
- スター
- 111k
- フォーク
- 14.3k
- 平均マージ
- 2日 4時間
- マージ済み PR(30日)
- 132
説明
TypeScript Version: 3.8.3
Search Terms:
type narrowing loose equality
type guard loose equality
loose comparison empty string zero
non-strict comparison empty string zero
type guard empty string zero
coercion double equals
type guard coercion fails
Code
TS misses edge cases when narrowing down types in loose equality comparisons.
Following the example from the new handbook on Equality narrowing, if you replace the strict equality with a loose equality, you're rocket is ready to explode. If you pass in the empty string and zero the if condition passes and accessing toUpperCase() on a number fails.
function foo(x: string | number, y: string | boolean) {
if (x == y) {
// We can now call any 'string' method on 'x' or 'y'.
x.toUpperCase();
y.toLowerCase();
}
else {
console.log(x);
console.log(y);
}
}
foo(0, "");
It might be worth mentioning, that this is only one out of many edge cases with the loose equality operator. Maybe you want to check more than just my example above. I bet Kyle Simpson (@getify) could give you some more examples.
Expected behavior:
After a loose equality comparison, TS should not narrow down string | number and string | boolean to string, since a number can equal a string in the edge case 0 == "".
Actual behavior:
After a loose equality comparison, TS narrows down string | number and string | boolean to string, even though this is incorrect, as seen for edge cases like 0 == "".
Playground Link: Playground Link
Related Issues:
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
TypeScript 3.8.3 を使用したリンク先の Playground reproduction から始め、0 == "" に対する JavaScript の loose equality の挙動と narrowing の結果を比較してください。equality-narrowing の挙動と関連するエッジケースを確認してください。runtime coercion によって比較が true になり得る場合に、checker がその例を安全に narrowed されたものとして扱わなくなれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- typescript
- 領域
- compilers
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 32/100