Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global module definition for typescript

I'm working on a project in Webstorm with the following file structure

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

I would like to make SomeInterface globally available (use the Interface without the need of an import).

My main index.d.ts is the following:

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

declare global {
  interface MainInterface extends SomeInterface {
    someAttribute?: number[]
    names: SomeInterface[]
    contactData: AnotherInterface[]
  }
}

Whenever I try to implement type definition in src/some/path/to/file.ts:

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

I get the following message: ESLint: 'MainInterface' is not defined.(no-undef)

This is my current 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"]
}

Am I missing something? I'm aware that making things globally available isn't recommended, however I was asked to to it in this way specifically.

like image 952
Byron Mh Avatar asked Sep 15 '25 22:09

Byron Mh


2 Answers

The typescript-eslint FAQ provides guidance here:

We strongly recommend that you do not use the no-undef lint rule on TypeScript projects. The checks it provides are already provided by TypeScript without the need for configuration - TypeScript just does this significantly better.

But no-undef is useful for JavaScript, so if you have mixed usage it's better to disable it only for files that are using TypeScript e.g. for Vue + TypeScript:

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

Of course don't then write Vue files using JavaScript since no-undef is disabled.

like image 98
xlm Avatar answered Sep 17 '25 18:09

xlm


If you define custom globals in your code, you need to tell ESLint about them: https://eslint.org/docs/user-guide/configuring#specifying-globals

Though, I would just consider turning off the no-undef rule though, as it's a check that's already covered by TypeScript itself.

like image 41
Brad Zacher Avatar answered Sep 17 '25 17:09

Brad Zacher