Typescript function that takes one or an array of objects

We use a simple declaration of a function quite a lot, where the function accepts either a single object or an array of objects of a certain type.

Simple announcement:

interface ISomeInterface { name: string; } class SomeClass { public names: ISomeInterface[] = []; public addNames(names: ISomeInterface | ISomeInterface[]): void { names = (!Array.isArray(names)) ? [names] : names; this.names = this.names.concat(names); } } 

But TypeScript throws "type not assignable" error.

Is there a better way to do this? Obviously, we can have two separate functions, but I think that managing a single vs-plural way is pretty good.

+6
source share
4 answers

You can make it easier

  addNames(names: ISomeInterface | ISomeInterface[]): void { this.names = this.names.concat(names); } 

From MDN

The concat () method returns a new array consisting of the array to which it is called, connected to the array (s) and / or the value (s) represented as arguments.

+8
source

You can also use the rest parameter:

 interface ISomeInterface { name: string; } class SomeClass { public names: ISomeInterface[] = []; // create an instance if applicable. addNames(...names: ISomeInterface[]): void { // the names argument will always be an array this.names = this.names.concat(names); } } 

You can call it like this:

 addNames(name1); // just pass one addNames(name1, name2, name3); // pass more comma separated addNames(...[name1, name2, name3]); // pass an array. 

Please note that I deleted the function keyword, because otherwise the this inside the body block may lose its scope depending on who calls it.

+6
source

The official typescript method handles this with several function signatures, for example:

 addNames(names: ISomeInterface): void; addNames(names: ISomeInterface[]): void; addNames(names: any): void { ... } 

You can find more detailed information in the official directory

+2
source

I think this is what you want

 interface ISomeInterface { name: string; } class SomeClass { public names: ISomeInterface[]; addNames(names: ISomeInterface | ISomeInterface[]): void { names = (names instanceof Array) ? names : [names]; this.names = this.names.concat(<ISomeInterface[]>names) } } 

You want to use instanceOf , not isArray.

0
source

All Articles