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...
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 !
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
If you have any idea of what I may be doing wrong, any help would be appreciated, thanks !
CodePudding user response:
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 moduleaxios
as a namespace (only types)import("axios").Axios
gets the typeAxios
from the namespaceimport 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
CodePudding user response:
Here is the solution:
import axios from "axios"
declare global {
var myOwnAxioss = axios
}
And that's it, you can now do this without any import, and with typings.
myOwnAxioss.get()