Both parameters for String.split() are optional. Calling .split() on a string with no parameters returns an array of the single string itself.
TypeScript Version: 2.7.2
Search Terms: string, split, string.split, .split, string.split(), .split()
Code
// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.
const arrayFunction = (args: string | string[]) => {
if (typeof args === 'string') {
args = args.split();
}
for (const arg of args) {
console.log(arg);
}
};
Expected behavior: No compilation errors.
Actual behavior: error TS2554: Expected 1-2 arguments, but got 0.
Not sure if we would want to change lib to support what seems like a mistake -- s.split() is just [s], right? (Similarly, Math.abs() won't fail at runtime, but you should have just written NaN.)
Correct. Given s = 'string', s.split() returns ['string']. And this does compile correctly. The error, however, is not correct. All parameters are optional in order to allow for this behavior, according to the spec.
There's a StackOverflow page for that by @RyanCavanaugh: https://stackoverflow.com/questions/41750390/what-does-all-legal-javascript-is-legal-typescript-mean
Aaaah, I see. Okay, that's fair. That ES allows for liberal coercions isn't reason enough for TS to open up that floodgate. Works for me! Thanks for your time!
@zulaica why would someone call split with no arguments on purpose? Just trying to understand if there's a scenario here
@RyanCavanaugh In this particular case, to allow me to write a more flexible function. In the above example, it stands to reason that the function could require an array, even if I'm only iterating on a single item. It's effectively something that, in this case, would just be nice.
The reason I initially posted this issue, though, is mostly because there isn't a way to coerce a single string into an array as cleanly as calling .split() on itself without any arguments. But really, what this finally boils down to is me falling back on old JS habits that I should not be doing with TS.
Refactoring args = args.split(); to args = [args]; in the above example is far more explicit than seemingly calling .split() arbitrarily.
TLDR; I don't see any reason to call split with no arguments simply to coerce a single string into an array because there are better ways. π