microsoft / microsoft/TypeScript

Directly setting an object which contains an optional item defined with an interface doesn't bypass `Object is possibly 'null' or 'undefined'.`

Open
#37,240 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: check: Control Flow
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.9.0-dev.20200305

Search Terms:

  • object is possibly 'null' or 'undefined'

Code
https://github.com/mckaysalisbury/typescript-direct-set

// See the above repo for a little more self containment.
// Most notably `"strictNullChecks": true`
interface I {
  optional?: (I | null);
  required: number;
}

let workaround: I;
workaround = {
  optional: { required: 2 },
  required: 1
};

workaround.optional.required;  // This is where the error occurs

Expected behavior:
This code should properly compile without errors, even with "strictNullChecks": true
Actual behavior:
With "strictNullChecks": true, there is a possibly undefined error.

Playground Link:
Typescript Playground

Related Issues:

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.

Research direction

Reproduce the example in the linked TypeScript Playground with strictNullChecks enabled, then read the related issues for the existing discussion of this behavior. Determine whether the compiler should narrow the optional property after the direct object assignment; done means an agreed behavior and a regression test covering the example if a change is accepted.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.