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
Search Terms:in operator type guard generic assert
Code
functionf<Kextendsstring,Textendsobject>(key: K,genericObj: T,concreteObj: {foo: string}){if('a'inconcreteObj){concreteObj.a// error, Property 'a' does not exist on type 'never'.}if('a'ingenericObj){genericObj.a// error, Property 'a' does not exist on type 'T'.}if(keyinconcreteObj){concreteObj[key];// error, Type 'K' cannot be used to index type '{ foo: string; }'}if(keyingenericObj){genericObj[key]// error, Type 'K' cannot be used to index type 'T'.}}
Actual behavior:
The compiler does not recognize that the objects have relevant keys even after checking for the existence of the key with the in operator. According to a comment by @sandersn, the in type guard (as implemented in #15256) narrows by eliminating members from a union; it does not assert that a key exists.
Desired behavior:
The compiler would assert that each object had a property with the relevant key, after having checked for the existence of the key with the in operator. Note that one possible implementation of an asserting type guard would look like
functioninOperator<Kextendsstring,Textendsobject>(k: K,o: T): o is T&Record<K,unknown>{returnkino;}
but this does not behave exactly as desired, possibly due to the bug in #18538: (not sure if #18538 was officially fixed, but it's not erroring anymore)
If a fix for #18538 appears and makes the g() function compile without error, great. Otherwise, maybe the property assertion for in could happen some other way. Not sure.
Related Issues: #10485, Treat in operator as type guard #15256, Add type guard for in keyword #18538, Error when mixing keyof and intersection type and type variable (fixed?)
(EDIT: #18538 seems to be fixed)
(EDIT: change any to unknown)
aoberoi, GregRos, SlurpTheo, olaf89, haltcase and 305 morechrisfls, jpidelatorre, vatosarmat, lffg, joshuakb2 and 37 moreSvish, a11delavar, sonallux, osnoser1, LukeSamkharadze and 17 more