typescript - 打字稿编译器允许重复类型声明
问题描述
我有两种类型 X。一种在文件中声明,另一种导入。当我使用此类型 X 声明变量时,编译器假定导入的类型。
文件1.ts
export type X = number
文件2.ts
import { X } from "./file2"
export type X = string
export const x: X = "foo" //this causes a compilation error
export const x: X = 42 //this works just fine
我注意到只有在导出本地类型时才会发生这种情况。如果未导出,您将在导入时看到冲突错误。
这是预期的行为还是 tsc 中的错误?
解决方案
我建议避免使用简单的别名完全隐藏您的导入/导出名称,以便
import { X } from "./file1"
变成
import { X as IWillNotShadowModulesAgain } from "./file1"
这样您就可以在同一个文件中使用这两个声明,例如
import { X as IWillNotShadowModulesAgain } from "./file2"
export type X = string;
const a:IWillNotShadowModulesAgain = 12;
const b:X = 'IPromise';
推荐阅读
- html - graphviz 中的展开/折叠表格
- python - 在 Python 或 PostgreSQL 中操作数据是否更快、内存效率更高?
- regex - 正则表达式选择第一个和最后一个引号字符
- php - symfony make:entity 在新项目上崩溃
- java - 为什么 ArrayBlockingQueue 构造函数使用 ReentrantLock 来获得可见性?
- javascript - 如何获得对我的 meme 命令的评论和赞成的数量?不和谐.js
- numpy - 将 VGG16 形状输出从 4096 个特征转换为 2048 个
- javascript - 有没有像 onChange 这样的函数也会监听 JavaScript 的变化?
- javascript - 如何让我的按钮用 javascript 做某事
- python - 合并 DataFrame 时的空结果