0

I have this function:

function proc(unames: Array<string>){}

I try to pass it this:

  import _ = require('lodash');

  const usernames = _.flattenDeep([unames]).filter(function (item, index, arr) {
     return item && arr.indexOf(item) === index;
  });

  const recipient = 'foobarbaz';
  proc(usernames.concat(recipient));

I get this error:

enter image description here

Does anyone know how to mitigate this?

I tried this, and I get an even longer and crazier error:

function proc(unames: Array<string | ReadonlyArray<string>>){}

however, this made the error go away:

function proc(unames: Array<string | ReadonlyArray<any>>){}

not really sure what's going on.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

1 Answers1

2

The warning seems to be referring to the use of .concat() rather than proc().

When called on an Array, such as usernames, TypeScript is validating that the arguments given to .concat() are also Arrays.

To resolve the warning, you have a few options:

  • Since you're using Lodash, its own _.concat() allows for appending individual values, and TypeScript's validation should be aware of that:

    const recipient = 'foobarbaz';
    proc(_.concat(usernames, recipient));
    
  • Define recipient as an Array or wrap it when calling .concat():

    const recipient = [ 'foobarbaz' ];
    proc(usernames.concat(recipient));
    
    const recipient = 'foobarbaz';
    proc(usernames.concat( [recipient] ));
    
  • You may also be able to configure TypeScript to validate for a later version of ECMAScript. Between 5.1 and 2015 (6th edition) of the standard, the behavior of the built-in .concat() was changed to support individual values (by detecting spreadable).

    For now, TypeScript is validating .concat() for 5.1 or older.

Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • 1
    @AlexanderMills Sorry. Correction: The method does support individual values now (starting with ECMAScript 2015, or the 6th edition), however TypeScript is still only considering it valid when the argument is an Array. – Jonathan Lonowski Mar 15 '18 at 04:20
  • yeah, that's weird, seems like `[].concat('foo')` has been supported by JS for awhile – Alexander Mills Mar 15 '18 at 04:45
  • @AlexanderMills That may be configurable, perhaps related to the target for build output, and array-only is just the default for highest compatibility. – Jonathan Lonowski Mar 15 '18 at 04:50