【问题标题】:Global module definition for typescript打字稿的全局模块定义
【发布时间】:2020-12-10 01:54:56
【问题描述】:

我正在 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"]
}

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

【问题讨论】:

  • 所以这个问题是关于使用 ES Lint 和 TypeScript 的?
  • @AluanHaddad 起初我不确定这是类型定义问题还是 linter 问题。根据 Brad 的回答,看起来这是一个 ESLint/TsLint 问题

标签: typescript eslint typescript-typings typescript-eslint


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    typescript-eslint FAQ 在这里提供指导:

    我们强烈建议您不要使用 no-undef lint 规则 打字稿项目。它提供的支票已经由 无需配置的 TypeScript - TypeScript 就可以 这明显更好。

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-06
      • 2016-09-05
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-28
      • 2018-02-11
      相关资源
      最近更新 更多