requiring typeof val == 'object' might be too strict.
val !== null && typeof val !== 'undefined' might be better