簡體   English   中英

如何在VSCode中使用JSDoc @template注釋ES5類,以防止出現checkJS錯誤?

[英]How to annotate an ES5 class with a JSDoc @template in VSCode to prevent checkJS errors?

我試圖用JSDoc注釋我的所有JavaScript函數和類屬性,以使用TypeScript和checkJS選項啟用正確的類型檢查。

但是,由於我想支持較舊的瀏覽器(IE9),並且不想使用Babel來轉譯代碼,因此需要使用ES5-era JavaScript,並且不能使用“類”來定義類。 因此,我需要求助於簡單的舊函數原型。

在我正在從事的項目中,我有以下課程:

/**
 * A condition class, executes a set function on results that meet their required conditions.
 * @class
 * @template T
 */
function Condition()
{
  /** @type {{condition?: boolean, result: T}[]} A list of conditions to execute. */
  this.list = new Array();
}

/** 
 * Adds a condition
 * @param {{condition: boolean, result: T}} condition The object with the condition and the result to be sent to the executing function.
 */
Condition.prototype.add = function(condition)
{
  this.list.push(condition);
}

/**
 * Executes the added conditions.
 * @param {function(T):void} action The function to be executed when a condition is true.
 */
Condition.prototype.execute = function(action)
{
  this.list.forEach(function(condition) { if(condition.condition) action(condition.result); });
}

在此類中, result元素在同一類實例中始終具有相同的類型,這使得它成為模板的完美用例,如代碼所示。

但是,當我嘗試使用例如以下代碼來使用該類時:

var conditionList = /**@type {Condition<string>} */(new Condition());
conditionList.add({ condition: true, result: 'yes' });
conditionList.execute(function(value) { console.log(value); });

我在VSCode中收到以下錯誤:

Type 'string' is not assignable to type 'T'. The expected type comes from property 'result' which is declared here on type '{ condition: boolean; result: T; }'

當我將鼠標懸停在conditionList ,彈出窗口顯示: var conditionList: typeof Condition

conditionList聲明更改為var /**@type {typeof Condition<string>} */(new Condition()); 也不起作用,並拋出一個錯誤,指出typeof Condition不能被轉換為typeof Condition

因此,在保持ES5類聲明樣式的同時,我不知道如何做才能允許模板工作。

但是,如果我將代碼轉換為ES6樣式的類( class Condition ),並且按原樣保留注釋,則代碼可以正常工作。 在那種情況下,將鼠標懸停在conditionList上將導致顯示一個conditionListvar conditionList: Condition<string>的彈出窗口,並且沒有錯誤。

有沒有辦法使用ES5樣式類獲得相同的行為? 我想念什么嗎? 還是在VSCode的TypeScript檢查器中未實現?

這似乎是一個錯誤,並且在Github中有一個未解決的問題。 不幸的是,直到TypeScript 3.3發布,它似乎都無法修復:

https://github.com/Microsoft/TypeScript/issues/26883

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM