使用泛型一致定义回调的 JSDoc 语法是什么?
我有以下身份函数的 JSDoc 定义:
/**
* @template T
* @callback id
* @param {T} x
* @returns {T}
*/
当我将它与普通函数定义一起使用时,它按预期工作,没有抱怨:
import { writable, derived } from 'svelte/store'
/**
* @template T
* @type {id<T>}
*/
function identity (x) {
return x
}
const number = identity(writable(42))
identity(derived(number, $number => $number * 2))
它正确地推断 number
是一个 Writable
(来自 Svelte 定义),因此 $number
是一个 number
。
然而,当在另一个函数中定义该函数时,从 identity
返回的类型会丢失:
/**
* @template T
* @param {(identity: id<T>) => unknown} definition
*/
function Model (definition) {
/**
* @template T
* @type {id<T>}
*/
function identity (x) {
return x
}
return definition(identity)
}
Model(function (identity) {
const number = identity(writable(42))
identity(derived(number, $number => $number * 2))
})
在这种情况下,number
是 any
,因此 $number
是 unknown
,因此它会抱怨:“算术运算的左侧必须是 'any'、'number'、'bigint' 类型或枚举类型”。
两者为何有差异?以及如何调整它以确保它推断出正确的类型?
谢谢!
I have the following JSDoc definition of an identity function:
/**
* @template T
* @callback id
* @param {T} x
* @returns {T}
*/
When I use it with a plain function definition, it works as expected, no complaints:
import { writable, derived } from 'svelte/store'
/**
* @template T
* @type {id<T>}
*/
function identity (x) {
return x
}
const number = identity(writable(42))
identity(derived(number, $number => $number * 2))
It correctly infers that number
is a Writable<number>
(from the Svelte definitions), and therefore $number
is a number
.
However when defining that function inside another one, the types returned from identity
are lost:
/**
* @template T
* @param {(identity: id<T>) => unknown} definition
*/
function Model (definition) {
/**
* @template T
* @type {id<T>}
*/
function identity (x) {
return x
}
return definition(identity)
}
Model(function (identity) {
const number = identity(writable(42))
identity(derived(number, $number => $number * 2))
})
In this case number
is any
, and therefore $number
is unknown
, and so it complains: "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."
Why is there a difference between the two? and how can it be tweaked to ensure that it infers the correct types?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论