如何导出包范围的 JSDoc 类型?

问题描述 投票:0回答:1

我正在

tsc
中寻找此错误的解决方法:https://github.com/microsoft/TypeScript/issues/50436

问题1:

包范围类型在包之外不可用。

    如果您在
  1. ./types.js
     中声明一个类型(并将该文件包含在 
    jsconfig.json.include
     中,那么该类型的范围仅限于您的包 - 任何文件都可以使用它。示例:
    
    // types.js /** * @typedef {Object} Foo * @prop {String} name */ // index.js /** @type {Foo} */ let foo;
    
    
  2. 不能从另一个包导入该类型。例子: // bar.js /** @type {import('foo/types.js').Foo} */ let foo; // ❌ [tsserver] Cannot find name 'Foo'.
    
    
问题2

导出类型在包范围内不可用。

    如果您将导出添加到
  1. ./types.js
    ,则这些类型在包级别不再可用。例子:
    
    // types.js module.exports = {}; // causes types to be exported /** * @typedef {Object} Foo * @prop {String} name */ // index.js /** @type {Foo} */ let foo; // ❌ [tsserver] Cannot find name 'Foo'.
    
    
  2. 但现在从另一个包导入该类型。例子:
  3. // bar.js /** @type {import('foo/types.js').Foo} */ let foo;
    
    
减少测试用例 Git 存储库

这是一个简化的测试用例,包含所有

tsconfig.json

package.json
 等:

https://github.com/coolaj86/test-case-tsc-exports

. ├── README.md ├── main.js ├── tsconfig.json └── node_modules ├── bar │ ├── bar.js │ ├── package.json │ ├── tsconfig.json │ └── types.js └── foo ├── foo.js ├── package.json ├── tsconfig.json └── types.js
第 22 条军规

如何才能同时导出类型

让它们在包范围内可用?

javascript typescript jsdoc tsc tsserver
1个回答
1
投票
问题是

foo/types.js

 声明了一个只能在其声明的包中访问的全局类型。这是因为 
foo/types.js
 不是一个模块,所以其中的所有内容都变成了全局的。来自
文档

仅当 TypeScript 找到

import

export
 时,文件才被视为模块。在某些基本情况下,您可能需要写出 
export {}
 作为一些样板以确保这一点。

要解决这个问题,

foo/types.js

bar/types.js
都应该有像
module.exports = {};
这样的导出(或者你在
bar/types.js
中编写的导出,甚至像
export {}
这样的ES模块)。

以下是

types.js

文件:

栏/types.js

"use strict"; /** * @typedef {Object} Bar * @property {Number} age * @property {2 | 7 | 11 | 37 | 42} lucky_number */ module.exports = {};

foo/types.js

"use strict"; /** * @typedef {Object} Foo * @property {String} name * @property {"vanilla"|"chocolate"|"strawberry"} flavor */ module.exports = {};
要在包级别使用该类型,它必须与在 Typescript 中相同,只需导入它即可。这样一切都应该按预期进行。

bar/bar.js

"use strict"; /** @type {import('./types.js').Bar} */ let bar = { age: 37, lucky_number: 37, }; console.log(bar);

foo/foo.js

"use strict"; /** @type {import('./types.js').Foo}*/ let foo = { name: "JS", flavor: "vanilla", }; console.log(foo);

main.js

"use strict"; /** * @param {import('foo/types.js').Foo} foo * @param {import('bar/types.js').Bar} bar */ function bazzer(foo, bar) { return { baz: foo.name, qux: foo.flavor, quux: bar.age, grault: bar.lucky_number, }; } module.exports.bazzer = bazzer;
这是已修复的存储库:

https://github.com/lepsch/test-case-tsc-exports

© www.soinside.com 2019 - 2024. All rights reserved.