You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
exportinterfaceMyType{a: number;b: string;c: Date;}interfaceMyOtherType{message: string;}constmyObj: Partial<Record<keyofMyType,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// allowedmyObj.a&&myObj.a.message// allowedconstmyKey: keyofMyType="a";myObj[myKey].message// not allowed - `Object is possibly 'undefined'`myObj[myKey]?.message// allowedmyObj[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
Uh oh!
There was an error while loading. Please reload this page.
I can't understand why i can gain access to a
Partial
object this waya.b && a.b.c
but not this way
a[keyof A] && a[keyof A].b
(when typeofa
isA
).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 variablekey
is of typekeyof myObj
. See example below to better understand.TypeScript Version: 3.8.3
Search Terms:
Code
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.
The text was updated successfully, but these errors were encountered: