Healthcare tends to be a huge expense for retirees. For some, it's their largest ongoing expense. That's why it's so important to save for it ahead of time.

In that regard, you have options. You could always pad your 401(k) or pump more money into your IRA. But if you're able to save for healthcare expenses in a health savings account, or HSA, it's generally in your best interest to do so.

The great thing about HSAs is that they're triple tax-advantaged. HSA contributions go in tax-free, and any funds you don't need to withdraw for medical bills right away can be invested in a tax-free manner. HSA withdrawals are also tax-free, as long as they're used to cover qualified healthcare expenses.

A person sitting on a couch with a laptop.

Image source: Getty Images.

Since HSA funds never expire, it's a great idea to fund an HSA during your working years, leave that money untapped, let it grow, and reserve it for retirement, when your healthcare costs might increase and the benefits you get from Social Security aren't nearly enough to cover them. But it's important to know how HSAs work once you sign up for Medicare. If you don't know the rules, you could end up with steep penalties on your hands.

Stop funding your HSA when you enroll in Medicare

Medicare eligibility begins at age 65. While you don't necessarily have to sign up for Medicare at that age if you're still working and/or are covered by a group health plan, you may want to.

For one thing, your costs under Medicare may be cheaper than they are under your group plan. Also, Medicare Part A, which covers hospital care, is free in the sense that enrollees aren't charged a premium for coverage. So you may decide that it makes sense to sign up for Part A alone around your 65th birthday so Medicare can serve as secondary insurance in the event of a hospital stay -- and perhaps pick up the tab your primary insurance won't.

But once you enroll in Medicare in any shape or form, you're barred from making HSA contributions. If you know you'll be signing up for Medicare, make sure to stop funding your HSA so you don't get penalized for making contributions when you're not allowed to.

You can use an HSA to cover Medicare costs

You can no longer contribute money to an HSA once you're on Medicare, even if it's only Part A. But you can absolutely use funds that are already in your HSA to cover Medicare expenses, from deductibles to copays. You can even use your HSA to pay your Medicare premiums (which, as mentioned, may not apply to Part A, but most definitely apply to Part B, which covers outpatient care, and Part D, which covers prescription drugs).

Having money in an HSA could make your healthcare costs under Medicare far more manageable. So it's a good idea to fund your HSA as long as you can. Just make sure you put an end to that practice once your Medicare enrollment becomes official.