If the pin will only be an input, a series resistor and a zener diode is usually best. Or a pair of clamping diodes.
For pins that will only be used as outputs, a similar approach can be used but obviously you would not want to use a higher value resistor (which affords much more protection). To really make things rugged enough to withstand 24V, you'd probably need to add a special buffer chip which is designed to withstand such abuse.
Optoisolators are usually required when you'll connect to other equipment that isn't grounded, or when Teensy won't be properly grounded and other stuff is. Optical isolation is also really helpful when one thing can be touched by humans (and must be properly grounded) and the other thing connects to an AC power line. Even though the neutral wire in AC power is usually connected to ground, it's considered very unsafe for anything humans can touch to have a connection to the neutral line of AC power. Optoisolators are pretty much always used in those sorts of applications.