Skip to content

Can not infer not null / undefined when use enum as the optional key #30714

Closed

Description

@taoalpha

TypeScript Version: 3.4.0-dev.201xxxxx

Search Terms:
enum as key
Code

enum A {
  a,
  b,
  c
}

type b = A.a|A.b

const a: {
  [key in A]?: {
    [key in A]?: string
  }
} = {
  [A.a]: {
    [A.a]: "a"
  }
}

function t() {
  // below line will have error on a[A.a][A.a] for possibly `undefined` when enabled `strictNullChecks`
  if (a[A.a] && a[A.a][A.a]) {
    return a[A.a][A.a];
    }
    return
}

Expected behavior:
no err when enable strictNullChecks, as the undefined should be ruled out after first a[A.a] check.

Actual behavior:

Object is possibly 'undefined'. for a[A.a][A.a]

Playground Link: https://www.typescriptlang.org/play/#src=enum%20A%20%7B%0D%0A%20%20a%2C%0D%0A%20%20b%2C%0D%0A%20%20c%0D%0A%7D%0D%0A%0D%0Atype%20b%20%3D%20A.a%7CA.b%0D%0A%0D%0Aconst%20a%3A%20%7B%0D%0A%20%20%5Bkey%20in%20A%5D%3F%3A%20%7B%0D%0A%20%20%20%20%5Bkey%20in%20A%5D%3F%3A%20string%0D%0A%20%20%7D%0D%0A%7D%20%3D%20%7B%0D%0A%20%20%5BA.a%5D%3A%20%7B%0D%0A%20%20%20%20%5BA.a%5D%3A%20%22a%22%0D%0A%20%20%7D%0D%0A%7D%0D%0A%0D%0Afunction%20t()%20%7B%0D%0A%20%20if%20(a%5BA.a%5D%20%26%26%20a%5BA.a%5D%5BA.a%5D)%20%7B%0D%0A%20%20%20%20return%20a%5BA.a%5D%5BA.a%5D%3B%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20return%0D%0A%7D

Activity

  1. RyanCavanaugh commented on Apr 2, 2019

    @RyanCavanaugh
    Member

    Duplicate #28081

  2. typescript-bot commented on Apr 5, 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.

  3. jcalz commented on Dec 23, 2019

    @jcalz
    Contributor

    The fix for #28081, namely #31478, did not address enum keys; should this be reopened or should a new issue be filed?

  4. 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