Typescript编译器允许重复的类型声明

时间:2019-07-25 09:20:51

标签: typescript

我有两种类型X。一种在文件中声明,另一种是导入的。 当我使用此类型X声明变量时,编译器将采用导入的类型。

file1.ts

export type X = number

file2.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中的错误?

1 个答案:

答案 0 :(得分:1)

我建议避免使用简单的别名来完全掩盖您的导入/导出名称,这样

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