microsoft / microsoft/TypeScript
Narrow typeof x === 'object' to Record<string | number | symbol, unknown> | null | unknown[]
まだ誰も着手していません。
- 主要言語
- Go
- スター
- 111k
- フォーク
- 14.3k
- 平均マージ
- 2日 4時間
- マージ済み PR(30日)
- 132
説明
Search Terms
typeof object narrow record
Suggestion
When narrowing a variable with typeof x === 'object', narrow to Record<string | number | symbol, unknown> | null | unknown[] instead of object | null.
Use Cases
When testing to see if something is an object, you almost always are starting out with unknown or similarly near-top level type and trying to narrow down to a lower "useful" type. When you use the typeof x === 'object' narrowing operation, currently TypeScript over narrows to the extremely constrained {} | null type. This suggestion would change that behavior to narrow down to the much wider Record<string | number | symbol, unknown> | null | unknown[], which the user can then choose to narrow more if they like, or they can choose to work with it as-is.
Examples
declare const apple: unknown
if (typeof apple !== 'object') throw new Error() // actual: object | null; desired: Record<string|number|symbol, unknown> | null | unknown[]
// uncomment this line and comment out the lines above to see desired behavior
// declare const apple: Record<string|number|symbol, unknown> | null | unknown[]
if (apple === null) throw new Error() // actual: object; desired: Record<string|number|symbol, unknown> | unknown[]
if (Array.isArray(apple)) throw new Error() // actual: object; desired: Record<string|number|symbol, unknown>
for (const key in apple) {
// Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
// No index signature with a parameter of type 'string' was found on type '{}'.
apple[key] // actual: error; desired: unknown
}
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- 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, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず issue の TypeScript 例を再現し、実際の narrowing と要求された結果を比較します。次に、typeof object の narrowing を担う型チェックの経路を追跡し、示されている null、配列、インデックスアクセスのケースのカバレッジを追加または更新します。これらの例がランタイム出力を変更せずに要求された union に narrowing されれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- typescript
- 領域
- compilers
- issue の種類
- 機能追加
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- 明確に書かれている
- 初心者へのやさしさ
- 35/100