I feel quick thinking is relatively tied to how relaxed you are at that point. When someone asks me something unexpected, I may or may not have something good as I might be a bit startled. A shopper sneaking up on me while my head is in a rack for example. But when I am at a cashier, I almost expect something and am relaxed.
For instance, I was buying a couple of tops once and the cashier goes "I'll bet these will look good on you." I replied "They will go great with the Capris I bought last week." She just giggled and moved on to small talk. Nothing embarassing there. Oh, and it was true.
Over time, you get more relaxed in various situations just on sheer repetition.