先來點背景關系。以下代碼以前是用 javascript 撰寫的,正在慢慢遷移到 typescript。不能對checkRecordsExists需要 typescript 的函式進行更改,因為檔案需要保留在 JS 中以避免它破壞我們使用它的其他所有內容。
我在 js 檔案中撰寫了以下函式(快速中間件):
module.exports.checkRecordsExists = (Model, { idName = 'id', paramLocation = 'path', optional = false, checkSource = true, additionalChecks, idDbField = 'id' } = {}) => {
...
};
并且根據VSCode,應該回退到空物件的函式物件引數是字串型別
(別名) checkRecordsExists(Model: object, { idName, paramLocation, optional, checkSource, additionalChecks, idDbField }?: string): (req: any, res: any, next: any) => Promise
當我嘗試在 ts 檔案中這樣呼叫它時,這導致 typescript 編譯器抱怨:
checkRecordsExists(dbService.CustomPage, { checkSource: false })
帶有以下錯誤訊息:
'{ checkSource: boolean; 型別的引數 }' 不可分配給“字串”型別的引數。ts(2345)
關于如何在不使用的情況下解決這個奇怪的錯誤的任何想法//@ts-ignore?
uj5u.com熱心網友回復:
為現有的 JS 檔案創建一個宣告檔案并不像看起來那么難。我必須承認,當第一次使用 Typescript 時,我如何將 TS 和 JS 混合在一起并不明顯,所以我想舉一個非常簡單的例子..
好的,讓我們開始吧。
假設我們在一個名為的檔案中有一個非常簡單的 hello 函式test.js
export function hello(a) {
console.log(`hello ${a}`)
}
現在假設我們總是希望引數 a 是 a string,并且它不回傳任何東西void。
我們所要做的就是test.d.ts在同一個目錄中創建一個名為的檔案,然后宣告就很簡單了。
declare namespace JS {
function hello(a:string):void;
}
export = JS;
現在當我們匯入test另一個 TS 檔案時,你會得到這個->
import {test} from "./test"
hello('there'); /*this is fine*/
hello(123); /*Argument of type 'number' is not assignable to parameter of type 'string'.*/
如果沒有.d.ts檔案,型別hello將為function hello(a:any):void..
另一種選擇,如果您被允許更改 JS 檔案,但不允許轉換為 Typescript,。Typescript 可以使用 JSDoc 語法。因此,執行以下操作將具有相同的效果。
/** @type {function(string):void} console logs hello param*/
export function hello(a) {
console.log(`hello ${a}`)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/490603.html
標籤:javascript 打字稿
