microsoft / microsoft/TypeScript

Type predicate for an optional property is not inferred

Open
#59,494 6 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

🔎 Search Terms

inferred type predicate optional

🕗 Version & Regression Information
  • This changed between versions 5.4 and 5.5
⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.5.4#code/C4TwDgpgBA8gRgKygXigbwPZmASwwOwEMAbAfgC51DL8BXAWzggCcBfVgKFElkQCYU6LLgIkKUWvgAmEAGY58EKaygAfIdjxFilNNSh1GLdh1OzJAYxH4oOAM4xNo4gBE5CpQAoIleAgCU6BwA9MFQ4RFQAHqkHJHMEMC0zDYQAHTCWiRQAITIqJIy8opSHJwc5vhWWrYOTtpuxUp83r78gWghYTFxEQlJKVDpmc65+RLS7iVlHEA

💻 Code
type Obj = {optional?: {a: number}}

function isOptionalDefined(e: Obj) {
    return e.optional !== undefined
}

if (isOptionalDefined(someObj) {
  someObj.optional.a // 'someObj.optional' is possibly 'undefined'
}
🙁 Actual behavior

If a type contains an optional property, and I write a function that ensures the property is defined, the function is not inferred as a type predicate. No type narrowing happens when I use this function.

At the same time, if I rewrite the original type to be itself a union, then the type predicate is inferred, as expected.

🙂 Expected behavior

Type predicate is inferred

Additional information about the issue

I feel it has something to do with https://github.com/microsoft/TypeScript/issues/55257, but I'm not sure.

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

Start with the TypeScript Playground reproduction linked in the issue and compare the 5.4 and 5.5 behavior for the optional-property predicate. Read the discussion in issue #55257 for related context; done means the predicate is inferred and the optional property narrows without an error in the provided example.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.