2

If I am calling a function that takes any how do I specify the type of an object literal that is passed in directly (without creating a local variable). This doesn't work:

      aMessageChannel.port1.postMessage({
        foo: 1,
        bar: 2,
      }: MyMessageType);
2
  • Why do you need to specify the type of the parameter if the function doesn't require it? Commented Apr 21, 2020 at 13:33
  • To ensure I get the object fields correct. Commented Apr 21, 2020 at 13:38

1 Answer 1

1

I'm not sure why you would need to specify an object's type at the place where it is called, you would usually do that in the function definition.

In the case where you are calling an outside function that accepts any - and because it's someone else's code you cannot change the function's signature - you can define your object with a type declaration first and then pass it into the function.

// if obj does not have the right shape to be a MyMessageType then the error will display here
const obj: MyMessageType = {
  foo: 1,
  bar: 2,
}

aMessageChannel.port1.postMessage(obj);
Sign up to request clarification or add additional context in comments.

2 Comments

Yes this is an obvious workaround, which is why I specifically said an object literal that is passed in directly (without creating a local variable).
TypeScript doesn't have syntax for that. Sorry.

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.