TypeScript files don't know about anything you've done in other TypeScript files unless they have a reference to them. So at the top of bar.ts you should have a line
/// <reference path="foo.ts" />
Answer from Jeffery Grajkowski on Stack OverflowTypeScript files don't know about anything you've done in other TypeScript files unless they have a reference to them. So at the top of bar.ts you should have a line
/// <reference path="foo.ts" />
From your question, not sure if it was a compilation, IDE or runtime issue that you had. Still, thought I'd share that a good way to avoid some of these issues with globals is to create your own "types" file and list it in your typeRoots property in your tsconfig.json.
For example, something I've done in the past is create a shortcut to console.log that also colours messages with a style I wish. Like so...
const pretty = (style: string, ...anything) => {
anything.forEach(something =>
console.log(`%c ${something} `, style));
return moment().format('[Logged @] HH:MM:SS');
}
So I don't have to declare var pretty in every TS file I use it, I'd create src/myTypes/globals/index.d.ts
...
declare function pretty(style: string, ...anything);
...
And then in my tsconfig.json
{
"compilerOptions": {
...
"typeRoots": ["src/myTypes"]
So, in your case, if foo was a var that you know would be there in runtime you could simply declare var foo: string; in your types file, list it in your typeRoots and use it happily in all your project files without any further config.
typescript global variables across files
Typescript Global Variable across Files
TypeScript how to declare global variable in every file? - Stack Overflow
How to define a global variable in a typescript module, which could be used in other modules directly without import?
Videos
Currently i'm using js-logger with babel-plugin-js-logger and @babel/plugin-transform-runtime, to make available a global logger function which can be invoked without any explicit imports. Rather we need to initialise the logger only once in the root module, say App.tsx, and it's automatically resolved at runtime by babel.
Currently when i use it in TypeScript, it's leading to linting as well as runtime errors.
This is the function that i use to initialise the logger in logger.ts:
import jsLogger from "js-logger";
const initializeLogger = () => {
jsLogger.useDefaults();
};
export default initializeLogger;
I invoke the above function once in App.tsx, within its useEffect. So I was thinking of adding a global function declaration for logger, such that TS is also able to understand what this function is all other files where i use say logger.info or logger.error etc.
I though adding the following to App.tsx would make this function available in all files.
import jsLogger from "js-logger"; declare var logger: typeof jsLogger;
But that doesn't seem to be working. Can anyone shed some light on this? What is the correct way to do this?
TypeScript files don't know about anything you've done in other TypeScript files unless they have a reference to them. So at the top of bar.ts you should have a line
/// <reference path="foo.ts" />
From your question, not sure if it was a compilation, IDE or runtime issue that you had. Still, thought I'd share that a good way to avoid some of these issues with globals is to create your own "types" file and list it in your typeRoots property in your tsconfig.json.
For example, something I've done in the past is create a shortcut to console.log that also colours messages with a style I wish. Like so...
const pretty = (style: string, ...anything) => {
anything.forEach(something =>
console.log(`%c ${something} `, style));
return moment().format('[Logged @] HH:MM:SS');
}
So I don't have to declare var pretty in every TS file I use it, I'd create src/myTypes/globals/index.d.ts
...
declare function pretty(style: string, ...anything);
...
And then in my tsconfig.json
{
"compilerOptions": {
...
"typeRoots": ["src/myTypes"]
So, in your case, if foo was a var that you know would be there in runtime you could simply declare var foo: string; in your types file, list it in your typeRoots and use it happily in all your project files without any further config.
I think I know what you're trying to do — you want typescript to understand that the p variable is set in the global scope without having to import { p } from ... in every file.
If I'm not mistaken, what you need to do is make an ambient declaration:
declare const p: (message: string) => void // or whatever
This doesn't have to be declared in every file. Put it in a d.ts file in a folder called typings/ and then include that file in your tsconfig:
"include": [
"typings/**/*",
...
],
Note: your d.ts file can't import any other modules. But it can use other ambient types that were declared in other d.ts files, without importing them. If you import something, then typescript will not treat your file as an ambient declaration and it won't work.
Smart move to abstract the logging so you don't end up with code throughout your program that depends directly on console.log.
You could declare it as it already exists globally:
declare var p: (message: any, ...additionals: any[]) => void;
But if you had to place this in every file, you might as well:
import { p } from './logging';
By making a logging module with your console.log wrapper.
globalThis is the future.
First, TypeScript files have two kinds of scopes
global scope
If your file hasn't any import or export line, this file would be executed in global scope that all declaration in it are visible outside this file.
So we would create global variables like this:
// xx.d.ts
declare var age: number
// or
// xx.ts
// with or without declare keyword
var age: number
// other.ts
globalThis.age = 18 // no error
All magic come from
var. Replacevarwithletorconstwon't work.
module scope
If your file has any import or export line, this file would be executed within its own scope that we need to extend global by declaration-merging.
// xx[.d].ts
declare global {
var age: number;
}
// other.ts
globalThis.age = 18 // no error
You can see more about module in official docs
Inside a .d.ts definition file
type MyGlobalFunctionType = (name: string) => void
If you work in the browser, you add members to the browser's window context:
interface Window {
myGlobalFunction: MyGlobalFunctionType
}
Same idea for NodeJS:
declare module NodeJS {
interface Global {
myGlobalFunction: MyGlobalFunctionType
}
}
Now you declare the root variable (that will actually live on window or global)
declare const myGlobalFunction: MyGlobalFunctionType;
Then in a regular .ts file, but imported as side-effect, you actually implement it:
global/* or window */.myGlobalFunction = function (name: string) {
console.log("Hey !", name);
};
And finally use it elsewhere in the codebase, with either:
global/* or window */.myGlobalFunction("Kevin");
myGlobalFunction("Kevin");
I'm trying to add a global variable in nodejs but it doesn't find them in other files, I have 2 problems
-
Typescript doesn't let me use
global.varname, onlyglobal['varname']. -
How do I declare the variable in another file?
You probably shouldn't be using a global variable for what you're trying to do, but…
to let TypeScript know about your own properties on the global object you need to augment the Global interface in a d.ts file:
export interface Global {
myProp: string;
}
If all you want is to 'share' stuff across files (i.e. modules) you probably want to export from your modules rather than add to the global object.
The language spec has a lot to say about ambient declarations using the keyword 'declare' in section 1.1
I'm pretty sure 'declare var myThing' is what you are looking for. I could also be wrong.