為什麼在編寫泛型函數時使用@type而不是@param和@return時,TS會提出投訴?
P粉464082061
P粉464082061 2024-04-03 12:10:23
0
1
329

TS為什麼抱怨這個:

/**
 * @template X
 * @type {function(X): X}
 */
const identity1 = (x) => x;

/**
 * @template X
 * @type {function(X): X}
 */
const identity2 = (x) => identity1(x);

TypeScript 錯誤訊息:

Type 'X' is not assignable to type 'X'. Two different types with this name exist, but they are unrelated.
  'X' could be instantiated with an arbitrary type which could be unrelated to 'X'.ts(2719)
graph.mjs(4, 14): This type parameter might need an `extends X` constraint.
const identity1: (arg0: X) => X
@template X
@type — {function(X): X}

但是,當使用 @param@return 更改 @type 時,它會正常工作:

/**
 * @template X
 * @param {X} x
 * @returns {X}
 */
const identity1 = (x) => x;

/**
 * @template X
 * @type {function(X): X}
 */
const identity2 = (x) => identity1(x);

我不明白為什麼。該文件並未提及這兩個簽章如何與泛型類型進行不同的互動。

P粉464082061
P粉464082061

全部回覆(1)
P粉448130258

使用 @type 標記引用的型別範圍僅限於大括號內。也就是說, @type {function(X): X} 不引用泛型類型,因為我們在範圍之外引用了 X。至少這是我的解釋。無論如何,不支援從 @type 提取提供的類型。

但是,您可以使用 @typedef 來超越功能:

/**  
* @template X  
* @typedef {X extends number ? [1, 2, 3][X] : never} Successor  
*/ 

/**  
* @template X  
* @typedef {X} Identity  
*/ 

/**
* @template X  
* @typedef {Identity>} Identity2  
*/

/** @type {Successor>} */ 
const x = 2;  

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!