Home > Back-end >  How to export methods to avoid writing import * as ...?
How to export methods to avoid writing import * as ...?

Time:10-14

Consider I have a file like this:

// Utilities.ts

export const appDateFormat = 'DD/MM/YYYY';

export const isNullOrWhitespace = (value: string | null | undefined): boolean => {
    if (value == null) {
        return true;
    }
    if (!value) {
        return true;
    }
    return value.trim().length <= 0;
};

export const formatDate = (date: Date): string => {
    return moment(date).format(appDateFormat);
};

From the outside, for example in a React Native component, I import those methods like this:

import * as Utilities from "../../services/Utilities";

And I invoke the methods like this: if (Utilities.isNullOrWhitespace(inputName)) ...

Another way to import is:

import {isNullOrWhitespace} from "../../services/Utilities";

And the usage is: if (isNullOrWhitespace(inputName)) ....

Personally, I prefer the first case because I like to see the "class" that exposes those methods, if the name is right (not this case), in my opinion it's a more expressive way to invoke methods.


My problems is that I always have to define the Utilities file and its methods to be able to write import * as Utilities which I don't like because, for example, WebStorm or Visual Studio Code intellisense never help me to add it automatically to my imports: I have to write it manually.

For example intellisense helps me instantly if I have an object like this:

// Colors.ts

export default {
    primaryColor: '#cc0001',
    accentColor: '#6db584',
}

...by automatically importing import Colors from "../../constants/Colors";


Is there a way to define the Utilities file and methods in order to avoid having to write the import section manually, in some way to help intellisense understand how to auto import the methods?

CodePudding user response:

You actually pretty much answered your own question with your export default example:

// Utilities.ts

export const appDateFormat = 'DD/MM/YYYY';

export const isNullOrWhitespace = (value: string | null | undefined): boolean => {
    if (value == null) {
        return true;
    }
    if (!value) {
        return true;
    }
    return value.trim().length <= 0;
};

export const formatDate = (date: Date): string => {
    return moment(date).format(appDateFormat);
};

export default {
    appDateFormat,
    isNullOrWhitespace,
    formatDate
}
  • Related