Add protection against invalid type.
Reduce code dupe, simplify (37 new lines, 500 gone). No functional change.