Skip to content

object is possibly undefined even though check is done #34535

Closed

Description

TypeScript Version: 3.6.3

Search Terms: object is possibly undefined

Code

const foo = (bar: { baz?: { name: string } }) => {
    const isBarBazDefined = !!bar.baz;
    if(isBarBazDefined) console.log(bar.baz.name);
}

Expected behavior:
Typescript should not give an 'object is possibly undefined' error.

Actual behavior:
Typescript does give an 'object is possibly undefined' error.

Playground Link:
http://www.typescriptlang.org/play/?ssl=4&ssc=2&pln=1&pc=1#code/MYewdgzgLgBAZiEMC8MAUAjAhgJwFwwDeM2AXgPwHFhYC2ApgdDgJZgDmMAvtwJQoA+IgCgYYmKEiwWEAEK55pACL04begBMUMAIQ7sOAHRkA3KPEs4aGfJyKVasJv6SIIADb1D7kO0y5jLFJDGgZeMy4gA

Related Issues:
Couldn't find any.

I realise this is very simple case, but I haven't been able to find an existing issue or FAQ entry on the subject...

Activity

  1. jack-williams commented on Oct 17, 2019

    @jack-williams
    Collaborator

    This is a duplicate of #12184 - narrowing results cannot be assigned to an identifier and reused.

  2. barroudjo commented on Oct 17, 2019

    @barroudjo
    Author

    Thanks. Is there any recommended workaround, besides again doing the check ?

  3. jack-williams commented on Oct 17, 2019

    @jack-williams
    Collaborator

    Jonathan Loss (@barroudjo) The quick and easy way is a ! assertion:

    const foo = (bar: { baz?: { name: string } }) => {
        const isBarBazDefined = !!bar.baz;
        if(isBarBazDefined) console.log(bar.baz!.name);
    }
  4. typescript-bot commented on Oct 20, 2019

    @typescript-bot
    Contributor

    This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

  5. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions