My answer is based on the one by Edward Casanova. I was about to edit it, but there are still quite a few differences to the code that works for me, plus I can now give some additional information on this.
This is based on TypeScript 4.3.5
// typings/globals.d.ts (depending on your tsconfig.json)
export {}
interface Person {
name: string
}
declare global {
var someString: string
var globalPerson: Person
}
This does not work without at least one export
(or import
) keyword. This turns this file into an ES module, which is necessary for this to work. You can export any of the statements or add an empty export {}
.
The code above adds types for the following handles:
someString
window.someString
globalThis.someString
globalPerson.name
window.globalPerson.name
globalThis.globalPerson.name
On the other side, the following is possible, but the result is different:
export {}
declare global {
let someLetString: string
const someConstString: string
}
This only adds types for the following handles:
someLetString
someConstString
As expected, you cannot assign any value to someConstString
. This might be useful for some older JS libraries that add the functionality to the global scope instead of exporting it. Libraries still can assign values to const
in this case because it's just a type, not a real const
. This const
is only known to TypeScript code. But be aware that let
and const
don't add properties to the global objects window
and globalThis
. So, var
might be the better choice here after all.
window
object can still work for me. But the need for a globalfoo
is required – Mistrust