Skip to content

Guarding against object value not being undefined fails when object value is typed with Partial<T> | undefined #53148

Closed
@bencooper222

Description

@bencooper222

Bug Report

🔎 Search Terms

  • full partial type guard union
  • enum as keys to interface with values possibly undefined or
  • undefined guard not compatible with Partial<T> | undefined

🕗 Version & Regression Information

I reproduced this on TS4.5, 4.8, 4.9, and 5.1.0-dev.20230306

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about Partials and undefined type guards

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.1.0-dev.20230306#code/JYOwLgpgTgZghgYwgAgCoQM5mQbwFDLIBGANnABYBcyWUoA5gNwHIwD2b1tDzAvnnlCRYiFAjbg4oaLhYBtANYQAnlzB0Q9ALrUACnChhgcEgB50WAHzIAPsgCuIACYQY0p3wHiQWZGyIAVtTeYFIgMgC8soRw1PiEhKQU1ABEcCkANCyE7JzIKUSZLLxZvMx43r7qyqjkmChRcmmZ+YVa5exQyAAUldhgbKhQyn4wyNW19QCU0cjAY93+AXIDQ8payACEUY4ubuFOM-EJlWwkEAB0JGz0i4Erg8NaF0nkU8yE-PxAA

💻 Code

interface Test {
  blah: string;
  foo: string;
}

interface container {
  [key: string]: Partial<Test> | undefined;
}

const obj: container = {
  a: {
    blah: "a",
    foo: "b",
  },
};

const tryThese = ["a", "b"];

for (const toTry of tryThese) {
  if (obj[toTry] != undefined) {
    // next line has error "Object is possibly 'undefined'.(2532)"
    console.log(obj[toTry].blah);
  }
}

🙁 Actual behavior

I specifically check if obj[toTry] is not undefined but TS still throws an error that obj[toTry] is potentially undefined. I suspect this is because Partial<T> is a superset of undefined.

🙂 Expected behavior

I want TS to not throw an error that obj[toTry] is undefined.

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