导入任何依赖项时,无法使用来自其他文件的接口

时间:2018-12-05 17:50:57

标签: typescript

我对接口导入有问题。当我在单独的文件中具有非导入依赖项的接口时,例如:

/src/app/something/something.interface.ts

interface ISomething {
    a: String[];
}

我可以在同一目录的另一个文件中使用它,而无需导入它,例如:

/src/app/someting/something.tsx

class Something extends React.Component<ISomething, any> {

}

但是当我有这样的界面时:

import Page from '../components/page';

interface ISomething {
    a: String[];
    b: Page;
}

编译过程中出现错误: [2] ERROR in src/app/something/something.tsx(9,40): error TS2304: Cannot find name 'ISomething'.

我尝试使用export interface ISomething ...并将其导入something.tsx,但这会导致错误

[2] ERROR in src/app/application/education/react/renderer/renderer.tsx(8,9): error TS2305: Module '"/Users/xxx/Projects/react/src/app/something/something.interface"' has no exported member 'ISomething'.

当我将ISomething界面放在something.tsx文件中时,它可以工作,但是我想在单独的文件中保持干净。

你知道为什么吗?

编辑: tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

tsconfig.app.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../dist/out-tsc/app",
    "module": "es2015",
    "types": [
      "node"
    ]
  },
  "exclude": [
    "src/test.ts",
    "**/*.spec.ts"
  ],
    "angularCompilerOptions": {
        "preserveWhitespaces": true
    }
}

1 个答案:

答案 0 :(得分:0)

这是由于Typescript中一些奇怪的默认行为(大多数是出于遗留目的)。默认情况下,如果文件中没有导入/导出语句,并且文件包含在tsconfig.json中(默认情况下,tsconfig的所有内容都直接包含在内),Typescript会将其视为 script ,而不是 module ,并使其标识符在全局范围内可用。

您可以通过更改tsconfig.json中modulecompilerOptions的值来禁用此行为。您想要哪个值取决于该代码的去向,但是例如,使用es6应该会为您提供所需的行为。

相关问题