The software controlling the light gun is also painting the picture on the TV. It knows where the scanning beam is at any given time, and its field of view is only a fraction of the set's screen, and it sees the scan flicker that we humans don't notice. When the light gun sees the scan get suddenly bright, the software knows exactly where that is in the picture, what scan line and how far across the screen.
You're right, the TV doesn't know, but the {game,cad-program,console} does.