Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript how to declare global variable in every file?

Tags:

typescript

I like to define a globally available helper

global.p = console.log.bind(console)

So I can use p('some message') instead of console.log('some message').

But TypeScript complains that p is undefined. Is there a way to tell the TypeScript compiler that there's a global variable p that's available in every file?

like image 684
Alex Craft Avatar asked Oct 15 '25 07:10

Alex Craft


1 Answers

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.

like image 63
2 revsMatthias Dailey Avatar answered Oct 18 '25 12:10

2 revsMatthias Dailey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!