Reputation: 55
I am new to Deno and TypeScript but have plenty of experience using NodeJs and Javascript, I have stumbled on an issue of sorts, that I could have easily sorted out in NodeJs by simply adding global
into the mix, however, that shows to be rather difficult in Deno for some reason.
I want to declare the First
variable that should be available globally everywhere without need to import it. (sort of like Deno
variable is available)
Here is an example of the code I'm trying to get running:
/// index.ts
import { FirstClass } from './FirstClass.ts';
global.First = new FirstClass();
await First.commit();
/// FirstClass.ts
import { SecondClass } from './SecondClass.ts';
export class FirstClass {
constructor() {}
async commit() {
const second = new SecondClass();
await second.comment();
}
}
/// SecondClass.ts
export class SecondClass {
constructor() {}
comment() {
console.log(First); // Should log the FirstClass
}
}
I would run this code like this:
deno run index.ts
Upvotes: 5
Views: 6290
Reputation: 86
If you were doing this to try and add in a Node.js global variable to Deno, you'll be glad to hear that in Deno 2.1 they added a new --unstable-node-globals
option to add in the nodejs globals automatically for you.
This will fix the runtime behavior, but you will still need to convince TypeScript this variable exists (it can't infer this from the command line in Deno 2.1), so you can fix this by adding the following code in your project:
declare global {
type Buffer = typeof import("node:buffer").Buffer;
}
Upvotes: 0
Reputation: 40444
The global object in Deno is: window
/ globalThis
window.First = new FirstClass();
For TypeScript compiler errors see: How do you explicitly set a new property on `window` in TypeScript?
declare global {
var First: FirstClass
interface Window { First: any; }
}
window.First = new FirstClass();
await First.commit();
Upvotes: 7