Skip to content

Type predicate for an optional property is not inferredΒ #59494

Open
@amakhrov

Description

@amakhrov

πŸ”Ž 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 #55257, but I'm not sure.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions