0

I have a set of plain JS functions defined in my index.html function. I would like to declare those functions to be able to use them in TypeScript files. This is what I do:

declare function getHtmlBasePath(): String;
declare function fbFetchedLoginStatus(): boolean;
declare function getFbAccessToken(): String;
declare function setFbAccessToken(token: String);

However, to avoid declaring those files in every TypeScript file where they are used, I would like to define them in a separate file and import that file wherever I want. This way, I void duplicate declaration and I also get the support of the IDE if I want to do refactoring later. However, by the time I define those declarations in a TypeScript file and import them, the TypeScript compiler will assume this is a module that actually has to be imported, while it is simply a declaration file (more like a header file for an external library in C/C++).

Is there a way to have a certain TypeScript serves no purpose other than set of a declaration, i.e. when you import it, TypeScript compiler doesn't generate require statements?

2 Answers 2

3

Export the function definition in a separate file using export keyword:

export function getHtmlBasePath(): String {
    // your code
}

TO use the function in any other typescript file, just import the function using the import keyword.

import {getHtmlBasePath} from 'filename';

filename is the name of the file where the function definition is written. After import the function you ca use the function as any other normal function.

Sign up to request clarification or add additional context in comments.

1 Comment

This is what I did actually, but it TypeScript compiler ended up treating the function declaration as a function and appended the module name to the name of the function, when what I wanted is actually just a way for TypeScript compiler to recognize that this function is defined globally.
0

The TypeScript compiler is smart enough not to transform those declarations into require statements. In fact, none of them will end up in your compiled JavaScript code.

1 Comment

Thanks, but that doesn't seem to be the case, as I see a dependency being added for the globals module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.