Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of types and interface without importing

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.

like image 758
Bijoy Avatar asked Aug 23 '18 10:08

Bijoy


1 Answers

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

like image 151
shohrukh Avatar answered Oct 15 '22 05:10

shohrukh