typescript 3.2 新編譯選項strictBindCallApply

突發錯誤

我的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選項,又能通過編譯的方案,煩請告知一下,謝謝!我若哪天找到方法,會馬上更新本文章。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章