I am having trouble with declaration files in TypeScript

89 views Asked by At

I'm trying to use the trace function in my TypeScript code, which has been declared in a .d.ts file as follows:

declare function trace(arg: string | number | boolean);
declare function trace(arg: { id: number; name: string });

However, when I try to use the trace function in my code in the file index.ts as follows:

trace("trace with string"); // calls the trace function with a string argument
trace(true); // calls the trace function with a boolean argument
trace(1); // calls the trace function with a number argument
trace({ id: 1, name: "test" }); // calls the trace function with an object argument

I get the following error:

ReferenceError: trace is not defined

Can anyone help and tell me what I am doing wrong? The declaration option is enabled in tsconfig.json too.

Thank you in advance.

EDIT:

Here is the JS code in a JS file where the trace function is being declared

var ErrorHelper = (function () {
    return {
        containsErrors: function (response) {
            if (!response || !response.responseText)
                return false;

            var errorValue = response.responseText;

            if (String(errorValue.failure) === "true"
                || Boolean(errorValue.failure)) {
                return true;
            }
            return false;
        },
        trace: function (msg) {
            var traceMessage = msg;
            if (msg.responseText) {
                traceMessage = msg.responseText.errorMessage;
            }
            console.log("[" + new Date().toLocaleTimeString()
                + "] " + traceMessage);
        }
    }
})();
1

There are 1 answers

0
sam it On

To make your function visible to other classes, you should also export it in the d.ts file:

You can find the information here: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html

declare function trace(arg: string | number | boolean);
declare function trace(arg: { id: number; name: string });
export = trace;
export as namespace trace;