首页 > 解决方案 > 如何在函数调用中指定对象类型

问题描述

如果我正在调用一个函数,该函数any如何指定直接传入的对象文字的类型(不创建局部变量)。这不起作用:

      aMessageChannel.port1.postMessage({
        foo: 1,
        bar: 2,
      }: MyMessageType);

标签: typescript

解决方案


我不确定为什么需要在调用对象的地方指定对象的类型,通常会在函数定义中这样做。

如果您正在调用一个接受的外部函数any- 因为它是其他人的代码,所以您无法更改函数的签名 - 您可以先使用类型声明定义您的对象,然后将其传递给函数。

// 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);

推荐阅读