Let $X$, $Y$, and $Z$ be topological spaces. Let $f:X \rightarrow Y$. Further assume that for every continuous function $g:Y \rightarrow Z$, $g \circ f$ is continuous.

Question: Under what conditions on the topology of $Y$ and/or $Z$ can we conclude that $f$ must then be continuous?

This is easily achieved if $Y$ is (essentially) homeomorphic with $Z$, but this seems like drastic overkill.

To me, this seems like some kind of 'universal property' for the continuity of $f$; or maybe some kind of generalized "uniformly continuous" condition? Note: original question due to Nick James, but he's not a big web user, so I am asking on his behalf.