typescript 3.2 新编译选项strictBindCallApply

5次阅读

共计 1038 个字符,预计需要花费 3 分钟才能阅读完成。

突发错误
我的 gels 项目(https://github.com/zhoutk/gels),几天没动,突然 tsc 编译出错,信息如下:
src/app.ts:28:38 – error TS2345: Argument of type ‘any[]’ is not assignable to parameter of type ‘[Middleware<ParameterizedContext<any, {}>>]’.
Property ‘0’ is missing in type ‘any[]’ but required in type ‘[Middleware<ParameterizedContext<any, {}>>]’.

28 m && (app.use.apply(app, [].concat(m)))
我的源代码,是动态加载 Koa 的中间件,app 是 koa2 实例
for (let m of [].concat(middleware)) {
m && (app.use.apply(app, [].concat(m)))
}
问题分析
几天前还是正常编译、正常运行的项目,突然出错,应该是环境变了。经查找,发现全局 typescript 已经升级到了最新版本,3.2.2,而项目中的版本是 3.0.3。将全局版本换回 3.0.3,编译通过,问题找到。
问题定位
上 typescrpt 的 github 主页,找发布日志,发现 3.2 的新功能,第一条就是:
TypeScript 3.2 introduces a new –strictBindCallApply compiler option (in the –strict family of options) with which the bind, call, and apply methods on function objects are strongly typed and strictly checked.
大概意思是:TypeScript 3.2 引入一个新的编译选项 –strictBindCallApply,若使用这个选项,函数对象的 bind,call 和 apply 方法是强类型的,并进行严格检测。
解决方案
因为是动态参数,想了半天我没法明确声明类型。因此,我在 tsconfig.json 配置文件中,设置 ”strictBindCallApply”: false,将这个编译选项关闭,这样就可以将 typescript 升级到 3.2.2 了。哪位朋友若有能打开 strictBindCallApply 选项,又能通过编译的方案,烦请告知一下,谢谢!我若哪天找到方法,会马上更新本文章。

正文完
 0