首页  >  问答  >  正文

为什么在编写泛型函数时使用@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 天前336

全部回复(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
  • 取消回复