Typescript 的全局模块定义

Byr*_* Mh 2 typescript eslint typescript-typings typescript-eslint

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

| src
    | ...
    | many files
| types
    | SomeInterface
        | index.d.ts
    | AnotherInterface
        | index.d.ts
    | index.d.ts
Run Code Online (Sandbox Code Playgroud)

我想使其SomeInterface在全球范围内可用(使用接口而不需要导入)。

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

import { SomeInterface } from './SomeInterface'
import { AnotherInterface} from './AnotherInterface'

declare global {
  interface MainInterface extends SomeInterface {
    someAttribute?: number[]
    names: SomeInterface[]
    contactData: AnotherInterface[]
  }
}
Run Code Online (Sandbox Code Playgroud)

每当我尝试在以下位置实现类型定义时src/some/path/to/file.ts

function someFunctionName(parsedData: MainInterface):void{...}
Run Code Online (Sandbox Code Playgroud)

我收到以下消息: 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"]
}

Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?我知道不建议让东西在全球范围内可用,但是我被特别要求以这种方式进行。

xlm*_*xlm 9

typescript -eslint 常见问题解答在这里提供了指导:

我们强烈建议您不要在 TypeScript 项目上使用 no-undef lint 规则。它提供的检查已经由 TypeScript 提供,无需配置 - TypeScript 只是在这方面做得更好。

no-undef对于 JavaScript 很有用,因此如果您混合使用,最好仅对使用 TypeScript 的文件禁用它,例如 Vue + TypeScript:

"overrides": [
    {
        "files": ["*.ts", "*.vue"],
        "rules": {
            "no-undef": "off"
        }
    }
]
Run Code Online (Sandbox Code Playgroud)

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


Bra*_*her 7

如果您在代码中定义了自定义全局变量,则需要将它们告知 ESLint: https: //eslint.org/docs/user-guide/configuring#specifying-globals

不过,我只是考虑关闭该no-undef规则,因为这是 TypeScript 本身已经涵盖的检查。