We analyze optical (UV rest-frame) spectra of X-ray selected narrow-line QSOs at redshift 1.5 < z < 3.7 found in the Chandra Deep Field South and of narrow-line radio galaxies at redshift 1.2 < z < 3.8 to investigate the gas metallicity of the narrow-line regions and their evolution in this redshift range. Such spectra are also compared with UV spectra of local Seyfert 2 galaxies. The observational data are inconsistent with the predictions of shock models, suggesting that the narrow-line regions are mainly photoionized. The photoionization models with dust grains predict line flux ratios which are also in disagreement with most of the observed values, suggesting that the high-ionization part of the narrow-line regions (which is sampled by the available spectra) is dust-free. The photoionization dust-free models provide two possible scenarios which are consistent with the observed data: low-density gas clouds (n < 10^3 cm^-3) with a sub-solar metallicity (0.2 < Z/Z_sun < 1.0), or high-density gas clouds (n ~ 10^5 cm^-3) with a wide range of gas metallicity (0.2 < Z/Z_sun < 5.0). Regardless of the specific interpretation, the observational data do not show any evidence for a significant evolution of the gas metallicity in the narrow-line regions within the redshift range 1.2 < z < 3.8. Instead, we find a trend for more luminous active galactic nuclei to have more metal-rich gas clouds (luminosity-metallicity relation), which is in agreement with the same finding in the studies of the broad-line regions. The lack of evolution for the gas metallicity of the narrow-line regions implies that the major epoch of star formation in the host galaxies of these active galactic nuclei is at z > 4.