microsoft / microsoft/TypeScript

Check truthy/falsy-ness for non-primitives to identify unreachable code

オープン
#44,840 コメント 3 件 リアクション 4 件 担当者 0 名 GitHub で見る

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

Awaiting More Feedback Experimentation Needed Suggestion
主要言語
Go
スター
111k
フォーク
14.4k
平均マージ
1日 19時間
マージ済み PR(30日)
117

説明

Suggestion

In some cases TypeScript can identify unreachable code and throws an error:

const isTrue = true;
if (isTrue === false) {
  console.log('Can never be reached.')
}

In other cases it is currently not possible, but it would be very helpful. (Maybe even with a suggestion what could have been meant - see array example.)

const isArray = ['hello'];
if (!isArray) {
  console.log('Can never be reached. You probably meant `if (!isArray.length) {`.')
}

const isObject = {};
if (!isObject) {
  console.log('Can never be reached.')
}

🔍 Search Terms

  • reachable / unreachable
  • dead code
  • condition
  • falsy / truthy
  • primitive / non-primitive
  • always

✅ Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code -> It can break code, but only to show potential bugs.
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Throw errors on unreachable code examples.

const isArray = ['hello'];
if (!isArray) { // error: This condition will always return false. Did you meant to check `isArray.length`?
  console.log('Can never be reached. You probably meant `if (!isArray.length) {`.')
}

const isObject = {};
if (!isObject) { // error: This condition will always return false.
  console.log('Can never be reached.')
}

// OR:
if (isArray) {
} else {
  console.log('Can never be reached. You probably meant `if (!isArray.length) {`.')
}

📃 Motivating Example

This week I saw a colleague which could have found a bug way sooner by introducing such a check. ❤️

💻 Use Cases

Finding bugs.

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

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

はじめの一歩

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

調査の方向性

まず、到達不能コードと条件に関する TypeScript の既存の診断を確認し、その挙動を issue の配列およびオブジェクトの例と比較します。truthy/falsy な非プリミティブをどのように報告すべきか、また提案されている length のガイダンスが適切かどうかを定義します。完了の条件は、出力される JavaScript を変更せずに、例が意図した診断を生成することです。

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

評価

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

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

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