Typescript: Is it possible to have a typings package apply only to some folder/files?

Created on 27 May 2017  ยท  8Comments  ยท  Source: microsoft/TypeScript

I have this TypeScript React application that runs on the browser and I'm using Jest for unit testing which runs on Node. I have my source code on /app and my test files on /test.

I often need to do global.something = jest.fn() on my tests but global is not defined. That comes from @types/node. But if I install that package, it will conflict with the application source.

For instance, where I could do const intervalId: number = setInterval(fn);, now I can't because of @types/node which has a different return type for setInterval of NodeJS.Timer which doesn't exist on the browser. The setInterval implementation on the browser returns a number (which is defined on the lib.dom.d.ts file).

So, is there a way I can have the Node.js typings apply just to the /test folder?

Needs More Info

All 8 comments

You could use multiple tsconfigs, with different settings for the --types option.

@andy-ms How could those different tsconfigs be applied to VS Code for each folder? AFAIK, VS Code only reads the root folder tsconfig file.

The language service should be able to find the correct tsconfig for a file when you view it. Try it out and tell me if you see any problems.

The language service should be able to find the correct tsconfig for a file when you view it.

I'm not sure how to configure these multiple tsconfig files so that the language service knows how to filter which one to use for each folder/file.

Use a structure like this:

โ”œโ”€โ”€ app
โ”‚ย ย  โ”œโ”€โ”€ a.ts
โ”‚ย ย  โ””โ”€โ”€ tsconfig.json
โ”œโ”€โ”€ node_modules
โ”‚ย ย  โ””โ”€โ”€ @types
โ”‚ย ย      โ””โ”€โ”€ node
โ”‚ย ย          โ””โ”€โ”€ ...etc...
โ”œโ”€โ”€ package.json
โ””โ”€โ”€ test
    โ”œโ”€โ”€ a.ts
    โ””โ”€โ”€ tsconfig.json

If you set app/tsconfig.json to have "types": [] in its compilerOptions and test/tsconfig.json to have "types": ["node"], trying to access global will show as a compiler error in app but will work in test.

That might work if you have an app and tests folder, but what if everything is in the same folder but with different names? For instance:

โ””โ”€โ”€ app
    โ”œโ”€โ”€ a.ts
    โ””โ”€โ”€ a.spec.ts

Is there a solution for this?

You could manually specify "files" or "include"/"exclude" to contain only the files you want.

Thanks for all your help :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Antony-Jones picture Antony-Jones  ยท  3Comments

Roam-Cooper picture Roam-Cooper  ยท  3Comments

remojansen picture remojansen  ยท  3Comments

CyrusNajmabadi picture CyrusNajmabadi  ยท  3Comments

dlaberge picture dlaberge  ยท  3Comments