typescript的全局模块定义



我正在Webstorm中进行一个具有以下文件结构的项目

| src
| ...
| many files
| types
| SomeInterface
| index.d.ts
| AnotherInterface
| index.d.ts
| index.d.ts

我想使SomeInterface全局可用(使用接口而不需要导入(。

我的主要index.d.ts如下:

import { SomeInterface } from './SomeInterface'
import { AnotherInterface} from './AnotherInterface'
declare global {
interface MainInterface extends SomeInterface {
someAttribute?: number[]
names: SomeInterface[]
contactData: AnotherInterface[]
}
}

每当我尝试在src/some/path/to/file.ts:中实现类型定义时

function someFunctionName(parsedData: MainInterface):void{...}

我收到以下消息:ESLint: 'MainInterface' is not defined.(no-undef)

这是我当前的tsconfig.json

{
"compilerOptions": {
"target": "esnext",
"allowJs": true,
"checkJs": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"noImplicitAny": false,
"baseUrl": "./",
"paths": {
"*": ["src/*"]
}
},
"include": ["src", "types/index.d.ts"],
"exclude": ["node_modules"]
}

我是不是错过了什么?我知道不建议在全球范围内提供东西,但有人特别要求我这样做。

typescript esint FAQ在这里提供了指导:

我们强烈建议您不要在TypeScript项目。它提供的检查已经由TypeScript不需要配置-TypeScript只需要这明显更好。

但是no-undef对JavaScript很有用,所以如果你有混合使用,最好只对使用TypeScript的文件禁用它,例如Vue+TypeScript:

"overrides": [
{
"files": ["*.ts", "*.vue"],
"rules": {
"no-undef": "off"
}
}
]

当然,不要使用JavaScript编写Vue文件,因为no-undef是禁用的。

如果在代码中定义自定义全局变量,则需要告诉ESLint:https://eslint.org/docs/user-guide/configuring#specifying-全球

尽管如此,我还是会考虑关闭no-undef规则,因为它是TypeScript本身已经涵盖的检查。

最新更新