Avoid invalid downcasts

Change-Id: Iea1688213cc0ebb8fcb3d3e3c862fd31275b9b38