We frequently use a simple function declaration where the function can accept either a single object or an array of objects of a certain type.
The basic declaration looks like this:
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);
}
}
However, TypeScript throws an "type is not assignable" error in this scenario.
Is there a more efficient way to accomplish this? While we could create two separate functions, I believe handling both single and multiple objects this way is sufficient.