Skip to content

Object is possibly 'undefined' when accessing Partial object via bracket notation #38091

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
nivzelber opened this issue Apr 21, 2020 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@nivzelber
Copy link

nivzelber commented Apr 21, 2020

I can't understand why i can gain access to a Partial object this way a.b && a.b.c
but not this way a[keyof A] && a[keyof A].b (when typeof a is A).

I have a use-case in which I can't use optional chaining. I want to conditionally render a React element like so {myObj[key] && <p>myObj[key].message</p>} when the type variable key is of type keyof myObj. See example below to better understand.

TypeScript Version: 3.8.3

Search Terms:

  • cant access partial type with Bracket notation
  • Bracket notation on Partial
  • access to partial type with Bracket notation failes to evaluate

Code

export interface MyType {
  a: number;
  b: string;
  c: Date;
}

interface MyOtherType {
  message: string;
}

const myObj: Partial<Record<keyof MyType, MyOtherType>> = {
  a: { message: "my message" },
  b: { message: "my message" },
  c: { message: "my message" }
};

myObj.a.message // not allowed - `Object is possibly 'undefined'`
myObj.a?.message // allowed
myObj.a && myObj.a.message // allowed

const myKey: keyof MyType = "a";
myObj[myKey].message // not allowed - `Object is possibly 'undefined'`
myObj[myKey]?.message // allowed
myObj[myKey] && myObj[myKey].message // not allowed - `Object is possibly 'undefined'` - why?

Expected behavior:
last line should work
Actual behavior:
Object is possibly 'undefined' error thrown when running tsc

Playground Link: https://codesandbox.io/s/mystifying-framework-5110c

Related Issues: #29642 is very similar but was closed for a being a duplicate of an issue from 2016 (?!). I don't think they are even related.

@MartinJohns
Copy link
Contributor

Duplicate #10530. Type narrowing does not occur for indexed access forms e[k] where k is not a literal.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Apr 21, 2020
@typescript-bot
Copy link
Collaborator

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants