microsoft / microsoft/TypeScript

Possible to narrow type of object literal property with strictNullChecks?

Open
#20,219 12 comments 0 reactions 1 assignee View on GitHub

@sandersn is already working on this.

Since Jan 30, 2018.

Committed Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.