To make high-performance semiconductor devices, a good ohmic contact between the electrode and the semiconductor layer is required to inject the maximum current density across the contact. Achieving ohmic contacts requires electrodes with high and low work functions to inject holes and electrons respectively, where the work function is the minimum energy required to remove an electron from the Fermi level of the electrode to the vacuum level. However, it is challenging to produce electrically conducting films with sufficiently high or low work functions, especially for solution-processed semiconductor devices. Hole-doped polymer organic semiconductors are available in a limited work-function range, but hole-doped materials with ultrahigh work functions and, especially, electron-doped materials with low to ultralow work functions are not yet available. The key challenges are stabilizing the thin films against de-doping and suppressing dopant migration. Here we report a general strategy to overcome these limitations and achieve solution-processed doped films over a wide range of work functions (3.0-5.8 electronvolts), by charge-doping of conjugated polyelectrolytes and then internal ion-exchange to give self-compensated heavily doped polymers. Mobile carriers on the polymer backbone in these materials are compensated by covalently bonded counter-ions. Although our self-compensated doped polymers superficially resemble self-doped polymers, they are generated by separate charge-carrier doping and compensation steps, which enables the use of strong dopants to access extreme work functions. We demonstrate solution-processed ohmic contacts for high-performance organic light-emitting diodes, solar cells, photodiodes and transistors, including ohmic injection of both carrier types into polyfluorene-the benchmark wide-bandgap blue-light-emitting polymer organic semiconductor. We also show that metal electrodes can be transformed into highly efficient hole- and electron-injection contacts via the self-assembly of these doped polyelectrolytes. This consequently allows ambipolar field-effect transistors to be transformed into high-performance p- and n-channel transistors. Our strategy provides a method for producing ohmic contacts not only for organic semiconductors, but potentially for other advanced semiconductors as well, including perovskites, quantum dots, nanotubes and two-dimensional materials.