When working with a third-party API that requires passing an array with an additional property, things can get a bit tricky. The standard approach involves creating a type like this:
type SomeArgument = string[] & { foo: string };
doSomething(argument: SomeArgument);
However, some developers find this method to be cumbersome and wordy.
An alternative solution that sacrifices type safety is using an object without defining a specific type:
const customArray: any = ['baz'];
customArray.foo = 'bar';
doSomething(customArray);
Alternatively, subclassing the Array class to create a more organized structure may seem cleaner but ends up being verbose:
class SomeArgumentImpl extends Array<string> {
constructor (public foo: string, content?: Array<string>) {
super(...content);
}
}
doSomething(new SomeArgumentImpl('bar', ['baz']));
Is there any better way to achieve this in a more concise manner? Perhaps something like
doSomething({ ...['baz'], foo: 'bar' });
? It's worth exploring for a one-liner solution, even though the example provided does not work as expected.