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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With