+ + default: + elog(ERROR, "cast jsonb field to %d is not supported.", targetOid);
is a little bit messy. This case should not be possible, because it is filtered by jsonb_cast_is_optimized. So the message should be changed or it needs a comment.
Yes, the double check is not necessary, that is removed in the attached v4 patch.