我正在
tsc
中寻找此错误的解决方法:https://github.com/microsoft/TypeScript/issues/50436
包范围类型在包之外不可用。
./types.js
中声明一个类型(并将该文件包含在
jsconfig.json.include
中,那么该类型的范围仅限于您的包 - 任何文件都可以使用它。示例:
// types.js
/**
* @typedef {Object} Foo
* @prop {String} name
*/
// index.js
/** @type {Foo} */
let foo;
// bar.js
/** @type {import('foo/types.js').Foo} */
let foo;
// ❌ [tsserver] Cannot find name 'Foo'.
./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'.
// bar.js
/** @type {import('foo/types.js').Foo} */
let foo;
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 条军规和 让它们在包范围内可用?
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;
这是已修复的存储库: