Warum beschwert sich TS, wenn beim Schreiben einer generischen Funktion @type anstelle von @param und @return verwendet wird?
P粉464082061
P粉464082061 2024-04-03 12:10:23
0
1
323

Warum sich TS darüber beschwert:

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

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

TypeScript-Fehlermeldung:

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}

Bei Verwendung von @param@return 更改 @type funktioniert es jedoch einwandfrei:

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

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

Ich verstehe nicht warum. In der Dokumentation wird nicht erwähnt, wie unterschiedlich diese beiden Signaturen mit generischen Typen interagieren.

P粉464082061
P粉464082061

Antworte allen(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;  

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!