首頁  >  問答  >  主體

為什麼在編寫泛型函數時使用@type而不是@param和@return時,TS會提出投訴?

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粉464082061P粉464082061180 天前338

全部回覆(1)我來回復

  • P粉448130258

    P粉4481302582024-04-04 10:26:28

    使用 @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;  
    
    

    回覆
    0
  • 取消回覆