People have mentioned how things can go wrong - it's always been smooth for me as long as I communicate. I've even gone a step or two further by going the other way around. For code I already have, I just tell my boss that I'm giving the company a free copy of the code. Then cover the license details in a written email. That probably brings better clarity than starting off talking about license details - "I'm giving the company a free copy of the software I wrote two years ago". Same as if they bought software from whomever, just the price is zero dollars.
You can, of course, use any license you want - it's your code. You could choose not to distribute it but use an open source license - that gives the company the right to distribute it, though. I've used a very simple license:
Acme Corp is hereby licensed by John Smith to copy modify, and
otherwise use Foo, written by John Smith. This license is perpetual
and assignable.
You can pull up on her examples of more detailed proprietary licenses if you wish.
I've also done it more than once with new code written partially for the employer, and I wanted to have it for future use. But only when the code isn't directly related to their core business. For instance, in a company that makes cars or appliances or bedsheets, maybe I write a module that makes querying and cross referencing Active Directory easier. I'll ask my boss if it's okay if I open source that on my Github (so I can have it at my next job). More often than not they say yes, provided there's nothing that references the company. They don't want to become responsible / liable or have any PR concerns or whatever by being connected to something they don't need to have their name on. Or be getting calls and emails for tech support. (That happened once when I accidentally left the internal documentation file in the repo).
Note I would NOT do that if I wrote some driver assist code for Toyota - cars are their core business. Of course they don't want to share that code with their competitors. Toyota management would likely be fine with open sourcing code related to checking that Windows machines have been patched - Windows security isn't the business they are in.