Chance
Chance

Reputation: 11323

Is there any way to avoid having to import from a @types file in TypeScript?

I'm building a project with TypeScript but I'm still getting used to it. I'm not sure that I'm going about it the best way. On the client, I'm maintaining a types files located in a @types dir off of the root src dir.

One of the things that seems off to me is having to import the definitions from said type file.

import { MultiSelectFilter } from '../../../@types';

I guess I need to make the client more domain driven so this doesn't feel as unnatural. I'm just curious if there is a way to avoid the need for this?

Thanks.

edit:

tsconfig.ts

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "declaration": true
  },
  "exclude": ["node_modules"],
  "include": ["global.d.ts", "next-env.d.ts", "**/*.ts", "**/*.tsx"]
}

Upvotes: 1

Views: 1601

Answers (1)

Rashomon
Rashomon

Reputation: 6792

You can create a global module. Use the extension .d.ts in a file at your root src. Then, every typescript file will be able to access the types declared there without importing them:

// src/global.d.ts

declare type MultiSelectFilter: any

Once done you can use all declared types in global.d.ts without importing them:

// src/index.ts

// import { MultiSelectFilter } from '../../../@types';  // You dont need this import anymore!
const multiSelectFilter: MultiSelectFilter; // This WORKS!

It's generally recomended to use file based modules and not polluting the global namespace.

Upvotes: 2

Related Questions