Rumah  >  Soal Jawab  >  teks badan

Mengapa TS mengeluh apabila menggunakan @type dan bukannya @param dan @return apabila menulis fungsi generik?

Mengapa TS mengadu tentang perkara ini:

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

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

Mesej ralat 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}

Namun, apabila menggunakan @param@return 更改 @type ia berfungsi dengan baik:

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

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

Saya tidak faham mengapa. Dokumentasi tidak menyebut cara kedua-dua tandatangan ini berinteraksi secara berbeza dengan jenis generik.

P粉464082061P粉464082061180 hari yang lalu330

membalas semua(1)saya akan balas

  • P粉448130258

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

    Gunakan @type 标记引用的类型范围仅限于大括号内。也就是说, @type {function(X): X} 不引用泛型类型,因为我们在范围之外引用了 X。至少这是我的解释。无论如何,不​​支持从 @type untuk mengekstrak jenis yang disediakan.

    Walau bagaimanapun, anda boleh menggunakan @typedef untuk mengatasi fungsi:

    /**  
    * @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;  
    
    

    balas
    0
  • Batalbalas