16

I recently moved to typescript to write React Native applications and one thing I have noted is that I can use types without importing/exporting them. I have placed all the definition files under the @types folder.

Is it the correct way of doing it without exporting and importing types?

If I import an external type from node_modules/ (say ViewStyle from react-native) and use it in my interface, it says "Cannot find the name" in VScode and I have to export the interface and import it where it's required to solve this.

I am trying to use the least possible amount of imports.

Puka
  • 1,485
  • 1
  • 14
  • 33
Bijoy
  • 399
  • 2
  • 7
  • 15
  • Please add the relevant code to the question. – Matt McCutchen Aug 23 '18 at 11:37
  • You should import the types. They are dependencies of the file and should be explicitly listed as such. Global types should only be used for global variables – Matt Bierner Aug 24 '18 at 13:47
  • 1
    See https://stackoverflow.com/questions/42233987/how-to-configure-custom-global-interfaces-d-ts-files-for-typescript?noredirect=1&lq=1 – Anton Feb 26 '20 at 22:43
  • Does this answer your question? [How to configure custom global interfaces (.d.ts files) for TypeScript?](https://stackoverflow.com/questions/42233987/how-to-configure-custom-global-interfaces-d-ts-files-for-typescript) – Puka Jun 16 '22 at 09:02

1 Answers1

8

First option:

You can use TS namespaces - it will reduce the amount of imports in your app (you don't have to import each type from namespace manually). For example, let's say we have app.namespace.ts file:

export namespace AppConfig {
  export interface BaseConfig {
    url: string;
    port: number;
  }

  export type MyMap<T> = {
    [key: string]: T;
  }

  export class Settings {
    public p1: boolean;
    public p2: number;
  }
}

Usage:

import { AppConfig } from './app.namespace';
// ...
baseConfig: AppConfig.BaseConfig;
myMap: AppConfig.MyMap<number>;
// ...

Second option:

Just create .d.ts files in your projects (usually each application sub module have its own models file, so you can create some-feature.d.ts inside your feature folder). In this case you can use any type from the d.ts files without importing.

Check this Stackblitz demo

shohrukh
  • 2,989
  • 3
  • 23
  • 38
  • 2
    What if I have a ton of interfaces and I don't want to have 20-30 interfacename.d.ts files hanging out in my main folder? I also don't want to put them all in the same file. How would you recommend handling this? – Urasquirrel Aug 06 '20 at 19:33