A lithium-doped magnesium hydride Li$_2$MgH$_{16}$ was recently reported [Y. Sun $et$ $al$., Phys. Rev. Lett. {bf 123}, 097001 (2019)] to exhibit the highest ever predicted superconducting transition temperature $T_{rm c}$ under high pressure. Based on first-principles density-functional theory calculations, we reveal that the Li dopants locating in the pyroclore lattice sites give rise to the excess electrons distributed in interstitial regions. Such loosely bound anionic electrons are easily captured to stabilize a clathrate structure consisting of H cages. This addition of anionic electrons to H cages enhances the H-derived electronic density of states at the Fermi level, thereby leading to a high-$T_{rm c}$ superconductivity. We thus propose that the electride nature of Li dopants is an essential ingredient in the charge transfer between Li dopants and H atoms. Our findings offer a deeper understanding of the underlying mechanism of charge transfer in Li$_2$MgH$_{16}$ at high pressure.