But you are forgetting that is Javascript the language doing it, not `new RegExp` doing that.
One could argue that `new Regexp` should maybe just check the type of the input and error if it is not the expected type, but thats likely expecting too much from Javascript Programmers.
This kind of thing is the reason why Typescript exists. I do agree checking the type of the argument would most likely be way more beneficial than not doing so. Seems like whoever wrote RegExp expects ppl will read the docs and use it “properly”. Can’t really say that’s a reasonable expectation 🤷♀️
The explanation is fairly straight forward - in apis where a string is expected, but a non-string is passed, JS will attempt to call .toString() on that method. Vanilla objects are the base case and return [object Object] when .toString() is called.
It would be a rather weird use case fo RegExp to need to recieve some object that intentionally implements toString in order to produce a valid regexp but that would be an inconsistency with standard expectations that .toString is the standard fallback.
This exists in other numeric apis too, where valueOf is attempted on objects.
View all comments
Show parent comment
9
u/TheLuminary Mar 20 '24
But you are forgetting that is Javascript the language doing it, not `new RegExp` doing that.
One could argue that `new Regexp` should maybe just check the type of the input and error if it is not the expected type, but thats likely expecting too much from Javascript Programmers.