This is an interesting problem. There is a somewhat convoluted solution, but you’ll need the latest version of AE (13.2.0.49).
This assumes that your text layer is named “text layer” and has the Typewriter preset applied.
Create an empty text layer named “temp” and add this expression for sourcetext:
txt = thisComp.layer(“text layer”).text.sourceText;
txt.substr(0,time)
Add a slider control to temp, and add this expression:
L = thisComp.layer(“text layer”);
r = sourceRectAtTime(time,true);
L.position[0]-L.anchorPoint[0]+r.left+r.width
(You can turn off the visibility eyeball for temp if you want).
Add a null named “right margin” to define your right margin.
Add this expression to your text layer’s range selector Start property:
maxX = thisComp.layer("right margin").toComp([0,0])[0];
s = thisComp.layer("temp").effect("Slider Control")("Slider");
for(i = 0; i < text.sourceText.length; i++)
if (s.valueAtTime(i) > maxX) break;
maxIdx = i-1;
Math.min(value,maxIdx)
Hopefully your type-on text will now stop before it exceeds the right margin.
Dan