I just needed to solve this very problem and I thought that some of you might need it later:
As user agent strings are both unreliable and about to be phased out, we need better ways to detect if the user has a touch-enabled device. Luckily, we have CSS4 media queries:
const deviceHasAMouse = window.matchMedia("(any-hover: hover)").matches;
See also MDN.
Enjoy.