typescript - 导出的变量 X 具有或正在使用来自外部模块 Z 的名称 Y,但无法命名
问题描述
{ compilerOptions: {declaration: true }}
在这种情况下,在我的 tsconfig.json 中使用 TS 3.9 时出现以下错误:
// a.ts
export const key = 1234
export const obj = {
[key]: 1
};
export default obj;
// b.ts
import A from "./a";
import { key} from "./a"
// Exported variable 'theExport' has or is using name 'key' from external module "c:/tsexample/src/a" but cannot be named.ts(4023)
const theExport = {
A: A,
B: 2,
C: 3,
};
export default theExport
// Exported variable 'theExport' has or is using name 'key' from external module "c:/tsexample/src/a" but cannot be named.ts(4023)
在对相关问题的评论中,当时 TS 的 PM 提出了两种解决方法:
- 显式导入类型
- 显式声明导出的类型(发生错误的地方)
(1) 在这种情况下不起作用。我尝试从“a”导出所有内容并在“b”中导入所有内容,但错误消息没有任何区别。
唯一有效的是这个非常冗长且难以维护的显式类型注释:
// updated b.ts
import A from "./a";
const theExport: {
// https://github.com/microsoft/TypeScript/issues/9944
[index: string]: typeof A | number;
} = {
A: A,
B: 2,
C: 3,
};
export default theExport;
我的问题是:
- 什么是我可以使用的不涉及重复对象形状的解决方法?
- 为什么导入类型不能解决问题?
这个问题与以下类似但不同:
- https://stackoverflow.com/a/44066867/2482570:不相关,因为它说问题已在 TS 2.9 中修复
- https://stackoverflow.com/a/49841010/2482570:没有一个答案提供适用于这种情况的解决方法
- Typescript 错误:“导出函数的返回类型具有或正在使用外部模块 <M> 中的名称 <n>,但无法命名”和键入错误“模块的默认导出具有或正在使用私有名称” - 从 typescript v1 切换。 8 到 2:在这种情况下,所提供的解决方案都不起作用
解决方案
它不是那么漂亮,但这是一个微创更改,似乎可以在沙箱中工作:
const theExport = {
A: A as {[K in keyof typeof A]: typeof A[K]},
B: 2,
C: 3
};
推荐阅读
- javascript - 你如何随机化某些数字?
- java - 如何在 NetBeans 上运行项目时删除“set build.dir”错误
- sql-server - 使用其他表中的值在表上创建主键
- unity3d - 在 Oculus 上突出显示触摸控制器按钮以进行教程
- mysql - MySQL 与 PostgreSQL 重复
- socket.io - Cloud Firestore - 两个播放器 - 检测断开连接 [Flutter]
- spring - 如何在多个假装客户端之一中禁用 hystrix
- java - 创建名为“userController”的 bean 时出错:通过字段“userService”表达的不满足的依赖关系
- python - 读取文件时的Python UnicodeEncodeError
- node.js - Websocket 431 错误:意外的服务器响应