'Create a global function like jest does

I am working on a meta framework that will use react.

I would like to offer some functions that are directly available without the need of an import, exactly like jest does with the function it(), beforeAll() etc...

Global function without import when jest is in the project

I basically succeed by simply declaring a typed var like this :

//myfile.d.ts
declare var someFunction : () =>  string

and then by assigning a function to it :

//someFile.ts
someFunction = () => "This is working"

Then, at the root of the project, I just imported once someFile.ts to make sure that someFunction was defined :

import "./someFile"

and yep, we are good, the function is global and does not require an import, and correctly typed !

Global function without import working

So , what is the problem ?

Well this work when I declare my type myself. But if I need to use a library's type to create my own type, it does not work anymore

Let say I want to make the axios object available globally without the need to have an import.

So here is what I did in the declaration file

import { Axios } from "axios"
interface MyOwnAxiosType extends Axios {}

declare var myOwnAxios:MyOwnAxiosType

But as soon as the import is added at the top, the myOwnAxios is not found anymore outside of this file

Global var not found when import added during the declaration

If you have any idea of what I may be doing wrong, any help would be appreciated, thanks !



Solution 1:[1]

Here is the solution: In a ts file

import * as axios_ from "axios"

declare global {
    var myOwnAxioss : typeof axios_.default
}
global.myOwnAxioss = axios_ as any

And that's it, you can now do this without any import, and with typings.

myOwnAxioss.get()

Solution 2:[2]

Using import in your file makes your declaration file a module and not an ambient declaration context.

Instead you will have to use this confusing syntax:

import Axios = import("axios").Axios;

interface MyOwnAxiosType extends Axios {}

declare var myOwnAxios:MyOwnAxiosType
  • import("axios") imports the module axios as a namespace (only types)

  • import("axios").Axios gets the type Axios from the namespace

  • import Axios = import("axios").Axios give the type above an alias

Using this kind of import will solve the issue because you are no longer using a static import.


If that doesn't work you can try inlining it:

interface MyOwnAxiosType extends import("axios").Axios {}

declare var myOwnAxios:MyOwnAxiosType

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2