4

I have a d.ts file with a variable declaration, like this:

declare var $: () => SomeValue;

And it is works good, in other places i can use this variable without import.

But, when i add some import from another module, this variable is not visible from other code.

import { SomeValue } from "./SomeModule";
declare var $: () => SomeValue;

What the syntax for this need?

1
  • It has nothing to do with declare. It has to do with the distinction between whether a file is assumed to be a script or a module. A module is a file containing 1 or more import or export statements. Declarations in a module are scoped to that module and must be exported for external consumption. Commented Jun 21, 2020 at 5:53

2 Answers 2

3

When .d.ts files use export or import, they become treated as a module instead of as ambient typings.

However you can still add to the global namespace using declare global. This allows you to augment global types, and even add new global types:

.d.ts

import { SomeValue } from "./SomeModule";

declare global {
    interface Window {
        $: () => SomeValue;
    }
    interface SomeGlobalInterface {
        x: number;
    }
}

.ts

// () => SomeValue
window.$

let value!: SomeGlobalInterface;
value.x;
Sign up to request clarification or add additional context in comments.

Comments

0

You'll need to add "export" keyword to the variable.

export declare var $: () => SomeValue;

If you want this variable to only be available in the same file, then it is not necessary to add "export" keyword. However, if you want it to be used in other files, then you'll need to add "export" keyword.

The same goes for constants, functions and classes. Adding "export" to it will make it available to be imported by other files.

Comments

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.