Carapaz had taken more than 90 seconds out of Del Toro’s lead after Wednesday’s stage 16 to reduce the 21-year-old’s advantage to 31 seconds.
However, Del Toro was the freshest of the riders during the descent of the 155km stage from San Michele all’Adige to Bormio to seal his success.
“Everyone wants this [pink jersey] and today I realised that I will never give up and I will always try and stay one step in front,” he said after becoming the race’s first Mexican stage winner in 23 years and the fourth youngest this century.
“I think this is my third or fourth podium in this year’s Giro – it’s incredible. I have nothing to lose. Today was not easier than yesterday but I had a better mentality.
“I did this last climb with the team and they gave me the confidence to go for it, full gas.”
Carapaz, the 2019 Giro winner, had tried again to break Del Toro on the Mortirolo, the main climb of the stage with an attack near the summit.
The Ecuadorian, 31, opened up a lead of around 30 seconds on Del Toro and Yates, who started the day 26 seconds behind in second place.
But Carapaz was caught again by the main favourites as they approached the short final climb of Le Motte before the descent to the finish.
And it was near the summit of Le Motte where Del Toro responded with his own attack – a move that only Carapaz could follow.
Riding together down the descent, they caught Bardet – the last survivor of the day’s breakaway – and would deny the 34-year-old his dream of a Giro stage success to complete his Grand Tour set in his final season as a professional.
With just under two kilometres to go, Del Toro was able to close in on Carapaz and, when he nipped in front, had the power to hold him off in the sprint.
Thursday’s 144km stage features three climbs in the first half of the race followed by flat terrain as the riders move from Morbegno to Cesano Maderno.