Typescript: String.split() with 0 Arguments Results in Compilation Error

Created on 23 Mar 2018  Β·  6Comments  Β·  Source: microsoft/TypeScript


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.

Working as Intended

All 6 comments

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.

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. πŸ™‚

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jbondc picture jbondc  Β·  3Comments

fwanicka picture fwanicka  Β·  3Comments

Roam-Cooper picture Roam-Cooper  Β·  3Comments

seanzer picture seanzer  Β·  3Comments

blendsdk picture blendsdk  Β·  3Comments