1

I'm using an existing 3rd party API over which I have no control and which requires me to pass an array with an additional property. Something like the following:

type SomeArgument = string[] & { foo: string };
doSomething (argument: SomeArgument);

Now I find it quite clumsy and verbose, to create SomeArgument while keeping the compiler satisfied.

This one works, but no type safety at all:

const customArray: any = ['baz'];
customArray.foo = 'bar';
doSomething(customArray);

Another option which feels cleaner, but is quite verbose (I will need different subclasses with different properties) is to subclass Array:

class SomeArgumentImpl extends Array<string> {
  constructor (public foo: string, content?: Array<string>) {
    super(...content);
  }
}
doSomething(new SomeArgumentImpl('bar', ['baz']));

Is there any better, one-liner-style way? I was hoping for something along doSomething({ ...['baz'], foo: 'bar' }); (this one does not work, obviously).

1 Answer 1

1

Suppose this is the function you want to call:

function doSomething (argument: string[] & { foo: string }) {
   argument.push("a");
   argument.foo = "4";
   console.log(argument);
}

Then you can call it like this:

// Works
doSomething(Object.assign(["a", "b"], { foo: "c" }));
// Error
doSomething(Object.assign(["a", 2], { foo: "c" }));
// Error
doSomething(Object.assign(["a", 2], { foo: 4 }));
Sign up to request clarification or add additional context in comments.

3 Comments

Not quite what I'm looking for: doSomething is actually a 3rd party library function over which I have no control. I just need to provide an argument of type string[] & { foo: string }, which I want to create as simply as possible. Thanks anyway!
Oh, I thought you're wrapping the library function with a function of your own. I see the problem now :) -- updated my answer.
Ahhh, the idea with Object.assign didn't come to my mind. Perfect!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.