网站搜索

typescript - 在不同文件中声明相同名称的类型时出现重复标识符


我有一个简单的 TypeScript 'snippets' 项目,但我遇到了一个问题,即多个 .ts 文件会有相同的类型名称(例如 Foo)。

//file-a.ts

type Foo = {

}
//file-b.ts

type Foo = {

}

如果我尝试编译这个,我得到:

 error TS2300: Duplicate identifier 'Foo'.

这对我来说没有意义——因为这些类型应该是针对该模块特定的。

我正在使用 TypeScript 版本 3.7.5,我的 tsconfig.json 有这些属性(其他所有设置都是默认值):

{
  "compilerOptions": {
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "outDir": "./dist",                        /* Redirect output structure to the directory. */
    "rootDir": "./src",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
    "strict": true,                           /* Enable all strict type-checking options. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  }
}

这里发生了什么?这里的实际代码。

答案#1

如果你没有从 TypeScript 文件中 export 任何内容,它会在全局作用域中编译。要使一个 .ts 文件成为封闭模块,你需要至少 export 一个内容。

答案#2

从 4.7 开始,TypeScript 提供了一个配置选项:编译器选项 moduleDetection 可以设置为 "force",这

确保每个非声明文件都被视为模块。

这将把所有输入视为模块(即使它们不包含任何 import 或 export 语句)。

相关文章