为什么在编写泛型函数时使用@type而不是@param和@return时,TS会提出投诉?
P粉464082061
P粉464082061 2024-04-03 12:10:23
0
1
327

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学习者快速成长!