microsoft / microsoft/TypeScript

Possible to narrow type of object literal property with strictNullChecks?

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

@sandersn がすでに取り組んでいます。

2018年1月30日 から。

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

説明

TypeScript Version: Current playground (2.6?)

Code

type Foo = {
  bar?: number[];
}

let f1: Foo = {};
f1.bar = [];
f1.bar.push(0);

let f2: Foo = { bar: [] };
f2.bar.push(0);

Expected behavior:

Both references to .bar compile successfully.

Actual behavior:

Second reference (f2.bar.push(0)) fails with "object is possibly undefined" -- the type of f2.bar is still treated as number[] | undefined even though it obviously can't be undefined.


This might not be an actual bug as such but whatever magic allows the compiler to narrow the type of f1.bar after assigning to it, should also be able to narrow the type when it was assigned in the literal.

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

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

はじめの一歩

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

評価

この issue はまだ評価されていません。

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

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