TypeScript 在JS中,jsdoc表示参数对象无法从包含函数中推断类型,

disbfnqx  于 7个月前  发布在  TypeScript
关注(0)|答案(2)|浏览(59)

🔎 搜索词

argument object infer

🕗 版本与回归信息

我在 next 中看到了这个问题,但我确信它一直是这样表现的。

⏯ Playground链接

https://tsplay.dev/WyQbbW

💻 代码

/** @type {(obj: Record<PropertyKey, unknown>, property: PropertyKey, value: unknown, nonEnumerable?: boolean | null, nonWritable?: boolean | null, nonConfigurable?: boolean | null, loose?: boolean) => void} */
module.exports = function defineDataProperty(
	obj,
	property,
	value
) {
	if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
		throw new TypeError('`obj` must be an object or a function`');
	}
	if (typeof property !== 'string' && typeof property !== 'symbol') {
		throw new TypeError('`property` must be a string or a symbol`');
	}
	if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) {
		throw new TypeError('`nonEnumerable`, if provided, must be a boolean or null');
	}
	if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) {
		throw new TypeError('`nonWritable`, if provided, must be a boolean or null');
	}
	if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) {
		throw new TypeError('`nonConfigurable`, if provided, must be a boolean or null');
	}
	if (arguments.length > 6 && typeof arguments[6] !== 'boolean') {
		throw new TypeError('`loose`, if provided, must be a boolean');
	}

	var nonEnumerable = arguments.length > 3 ? arguments[3] : null;
	var nonWritable = arguments.length > 4 ? arguments[4] : null;
	var nonConfigurable = arguments.length > 5 ? arguments[5] : null;
	var loose = arguments.length > 6 ? arguments[6] : false;
};

🙂 预期行为

arguments[3](以及4、5和6)都应该具有函数类型中定义的类型(在这个例子中,前三个应该是 boolean | null,第四个是 boolean)。
这应该导致 nonEnumerablenonWritablenonConfigurable 的类型为 boolean | null,而 loose 的类型为 boolean

🙁 实际行为

这四个变量的类型为 any

关于问题的附加信息

这是在启用 allowJs/checkJs 的 .js 文件中使用 jsdoc 的情况。

xzlaal3s

xzlaal3s1#

一个简单的示例来展示正在发生的事情:

/** @type {(s: string) => void} */
function fn(s) {
	// ^?
	// s: string

	const x = arguments[0];
	//    ^?
	// x: any, could be string
}
ilmyapht

ilmyapht2#

谢谢:)
当我编写一个具有可选参数的函数,但针对缺少参数默认值的环境时,这一点尤为重要。

相关问题