typescript - 如何在函数调用中指定对象类型
问题描述
如果我正在调用一个函数,该函数any
如何指定直接传入的对象文字的类型(不创建局部变量)。这不起作用:
aMessageChannel.port1.postMessage({
foo: 1,
bar: 2,
}: MyMessageType);
解决方案
我不确定为什么需要在调用对象的地方指定对象的类型,通常会在函数定义中这样做。
如果您正在调用一个接受的外部函数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);
推荐阅读
- c# - 在Json文件中添加一行Json
- spring - mongoDB文档上的读锁
- php - 为什么没有 assoc 的 json_decode 在 PHP 5.6 和 PHP 7.2 上的工作方式不同
- laravel - Laravel 5:有条件的雄辩关系方法
- java - Apache Camel 内存不足异常
- r - R 使用 mcapply() 使用多个内核而不使用循环
- javascript - 从特定 IP 地址服务 webpack 开发服务器
- mysql - 如何从记录中提取列值
- javascript - 使用 Graph API 无法使用过滤器参数获取特定日期的事件
- regex - 正则表达式多重匹配