I have a new Magic Keyboard 2 and I was wondering if keeping it connected all the time to the USB port can somehow damage the battery
In general, keeping it connected all the time will not damage the battery. Apple has designed these peripherals to only accept a charge when it's needed. When it doesn't need the power, it simply will not use it.
However, it's a good practice to periodically, every month or so, unplug the keyboard and let it run on its battery until it gets very low (below 10%) or stops working. Then you can plug it back in and leave it alone while it charges. Apple has a nice section on batteries and their maintenance here.
I believe Apple devices use 'smart' charging, where the device will only charge when it needs it, and won't be continuously subjected to charging (this only makes sense). The energy needs of the device, above maintaining the battery, will most likely come through the power connection (charging cable).
But as for running the battery down low to preserve it?
That is a bit more dubious.
- I believe the biggest question here is whether the device is EVER intended to be used intermittantly or frequently disconnected from a power source (in other words: run off of the battery). If the answer is 'no', then leaving it plugged in all the time will probably allow the battery to last the longest.
Remember, ANY rechargeable battery has a maximum or finite number of charge/discharge cycles.
If it's ALWAYS going to be tethered to power, there's no need to disconnect and discharge it (only to then reconnect and recharge it). By doing that, you would DEFINITELY use another one of the (finite number of) cycles (and for no reason).
References to battery 'health' pertain only to batteries that will be regularly 'cycled'. If the battery is not going to be cycled, then avoiding using up those discharge/recharge cycles will allow that battery to last longer than purposely discharging it for 'health'.
I have a Macbook from May 2012, with the original battery. It's been tethered nearly permanently since then (only a few times running on battery during power failures, or accidentally knocking off Mag-Safe connector). The Macbook charge icon always shows 100%, and there're never any battery warnings. (When the Macbook has very infrequently discharged and went low, it has always recharged back up to 100%; and that happened even within the last half-year... remember, the battery is going on 9 years old.)
I'm not sure of the algorithms used by Apple in determining 'battery health'. It could be that one of them is simply a clock; if the battery is so many years old, or if the device has been 'on' for so many hours, it may flag it as needing replacement. Another algorithm could calculate the number of equivalent full cycles, and compare to a some finite assigned number to that battery.