首页 > 解决方案 > 打字稿编译器允许重复类型声明

问题描述

我有两种类型 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 中的错误?

标签: typescript

解决方案


我建议避免使用简单的别名完全隐藏您的导入/导出名称,以便

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';

推荐阅读