Search code examples
typescriptjestjstypescript-typingstsconfig

Adding TypeScript ambient declarations only to specific files (like *.spec.ts)


My Jest setupTests file defines a number of global identifiers (like global.sinon = sinon, but typing them in ambient declarations applies to all files, not just the *.spec.ts where the setupTests file is included. Previously I've solved this by having a separate tsconfig.json file for the tests directory, but that is not possible if the test and non-test files are in the same directory. Is there any way to have ambient declarations that only apply to a specific file name pattern? Something like this:

declare module "*.spec.ts" {
    // declarations here
}

Solution

  • You cannot solve this problem by doing this:

    declare module "*.spec.ts" {
      /* ... */
    }
    

    because that's how you describe the contents of all *.spec.ts files, not the environment in which they executed.

    It's best if you can separate your source code from tests and use two separate tsconfig.json files. If you must have your source code and tests mixed, the only option that comes to mind is creating a declaration file outside of your included files and importing it manually in every test file. For example, you could create a directory called environment in the root of your project and put a test.d.ts file there.

    ./environment/test.d.ts

    declare const foo: string;
    

    Now, every test that depends on the global foo will need to reference environment/test.d.ts.

    ./path/to/foo.spec.ts

    import '../environment/test';
    
    console.log(foo);
    

    This is cumbersome, but I haven't found a better way to serve different globals for different files. Usually, people just pollute their global namespace with all globals they might have (Node, browser, tests).