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
{{ message }}
Repository navigation
"Property does not exist" error on union type even though all union members implement interface #26204
Search Terms: Property does not exist union type implements interface
Code
interfaceIGameObject{onEvent?: (event)=>void;}classPlayerimplementsIGameObject{}classEnemyimplementsIGameObject{}typeMovingObjects=Player|Enemy;constmovingObjs: MovingObjects[]=[];for(constobjofmovingObjs){// Error: "Property 'onEvent' does not exist on type 'MovingObjects[]'.""if(movingObjs.onEvent){movingObjs.onEvent('someEvent');}}
Expected behavior:
I would expect to be able to check if the method onEvent is present on the objects because they implement the interface, even though none of them implement the method yet. Some of them may implement it in the near future, so I want this check there to be safe. In my actual code, the interface also has non-optional properties that the classes do implement.
Actual behavior:
The compiler throws an error for "Property 'onEvent' does not exist on type 'MovingObjects[]'".
Unfortunately, implementing an interface doesn't actually declare those members in the class. You'll need to explicitly declare onEvent (even as an optional member) in Player and Enemy.
Activity
DanielRosenwasser commentedon Aug 4, 2018
Unfortunately, implementing an interface doesn't actually declare those members in the class. You'll need to explicitly declare
onEvent(even as an optional member) inPlayerandEnemy.typescript-bot commentedon Dec 14, 2018
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.