Repository navigation
instanceof Object does not work with the in operatorΒ #51007
Description
Activity
MartinJohns commented
on Sep 30, 2022 ContributorMore actionsYou can just use
typeof table === 'object', which will also work for objects without prototype chain (e.g.Object.create(null)).dragomirtitian commented
on Sep 30, 2022 ContributorAuthorMore actionsMartin Johns (@MartinJohns) That is the workaround I used, forgot to mention it. I still think ideally it should work.
- addedBugA bug in TypeScriptA bug in TypeScriptHelp WantedYou can do thisYou can do this
on Sep 30, 2022 RyanCavanaugh commented
on Sep 30, 2022 MemberMore actionsI think
instanceofis preferable sincetypeofcan return"function"for things that are stillinstanceof ObjectAndarist commented
on Sep 30, 2022 ContributorMore actionsThe
unknowntype gets narrowed down to{}thanks to!!table. Should we then allow a{}->object(Object?) transition through thistable instanceof Object?RyanCavanaugh commented
on Sep 30, 2022 MemberMore actionsI don't see why not -- narrowing should generally be transitive (i.e. if
A -x-> Cis ok thenA -y-> B -x-> Cshould be as well)Should we open a new issue for this problem, or does it belong here?
export function isHTMLTable<T extends object | null>(table: T): boolean { return !!table && 'html' in table; // error! // Type 'NonNullable<T>' may represent a primitive value, which is not permitted as // the right operand of the 'in' operator.(2638) }
Andarist commented
on Nov 11, 2022 ContributorMore actionsJoe Calzaretta (@jcalz) I'd say that this is a different problem as the issue here, at least from my PoV, was very related to
instanceof. The issue in this playground is related to generics, this one works just alright:export function isHTMLTable(table: object | null): boolean { return !!table && 'html' in table; }
Reacted by Joe Calzaretta- addedFix AvailableA PR has been opened for this issueA PR has been opened for this issue
on Nov 23, 2022 - locked as resolved and limited conversation to collaborators
on Oct 22, 2025
Bug Report
π Search Terms
instanceof Objectinπ Version & Regression Information
β― Playground Link
Playground Link
π» Code
π Actual behavior
Error: Type '{}' may represent a primitive value, which is not permitted as the right operand of the 'in' operator
π Expected behavior
Should type check
Notes
Seems to be introduced by #50666 which correctly introduces an error if
inis used on non objects. The issue is that it does not handle testing for objects withinstanceof Object