Home > database >  How To Get Typescript Compiler To See My Global Types?
How To Get Typescript Compiler To See My Global Types?

Time:11-21

I have defined some global interfaces as follows in top level of the project:

globaltypes.ts

declare global {

    my_interface {
        name:string
    }
}

But when i try to compile with ts-node, the compiler fails to compile with

"cannot find name "my_interface" ... diagnostic code "2304"".

My IDE recongizes the types as global, giving me autocomplete, but how do i get the compiler to do so also such that i can build the project?

tsconfig:

{
    compilerOptions {
        target: "ES2020"
        module: "commonjs"
        moduleResolution: "node"
        baseUrl: "./"
        allowjs: true
        allowSyntheticDefaultImports: true
        esModuleInterop: true
        forceConsistentCasingInFileNames:true
        strict: true
        typeRoots: ["./"]
        skipLibCheck: true
    }
   "exclude": ["node_modules", "./build/**/*"],
   "include": ["./**/*.ts"]

}

If i move the interface declaration into my main.ts file it works fine. I would rather not do this however as i want to access the interface elsewhere also, preferably without importing it.

CodePudding user response:

You need either remove declare global and import this type or you need to define it in file with .d.ts extension (see ambient declarations).

https://www.typescriptlang.org/docs/handbook/modules.html#ambient-modules https://basarat.gitbook.io/typescript/type-system/intro/d.ts

  • Related