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

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

🔎 搜索词

argument object infer

🕗 版本与回归信息

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

⏯ Playground链接

https://tsplay.dev/WyQbbW

💻 代码

  1. /** @type {(obj: Record<PropertyKey, unknown>, property: PropertyKey, value: unknown, nonEnumerable?: boolean | null, nonWritable?: boolean | null, nonConfigurable?: boolean | null, loose?: boolean) => void} */
  2. module.exports = function defineDataProperty(
  3. obj,
  4. property,
  5. value
  6. ) {
  7. if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
  8. throw new TypeError('`obj` must be an object or a function`');
  9. }
  10. if (typeof property !== 'string' && typeof property !== 'symbol') {
  11. throw new TypeError('`property` must be a string or a symbol`');
  12. }
  13. if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) {
  14. throw new TypeError('`nonEnumerable`, if provided, must be a boolean or null');
  15. }
  16. if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) {
  17. throw new TypeError('`nonWritable`, if provided, must be a boolean or null');
  18. }
  19. if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) {
  20. throw new TypeError('`nonConfigurable`, if provided, must be a boolean or null');
  21. }
  22. if (arguments.length > 6 && typeof arguments[6] !== 'boolean') {
  23. throw new TypeError('`loose`, if provided, must be a boolean');
  24. }
  25. var nonEnumerable = arguments.length > 3 ? arguments[3] : null;
  26. var nonWritable = arguments.length > 4 ? arguments[4] : null;
  27. var nonConfigurable = arguments.length > 5 ? arguments[5] : null;
  28. var loose = arguments.length > 6 ? arguments[6] : false;
  29. };

🙂 预期行为

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

🙁 实际行为

这四个变量的类型为 any

关于问题的附加信息

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

xzlaal3s

xzlaal3s1#

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

  1. /** @type {(s: string) => void} */
  2. function fn(s) {
  3. // ^?
  4. // s: string
  5. const x = arguments[0];
  6. // ^?
  7. // x: any, could be string
  8. }
ilmyapht

ilmyapht2#

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

相关问题