#How can I properly extend globalThis?

20 messages · Page 1 of 1 (latest)

haughty edge
#

i'm facing an issue where I can't properly extend globalThis. this is basically the setup that I have...

src/globals.d.ts:

export {};

interface Foo {
  x: number;
}

declare global {
  let foo: Foo;
  // uncomment bottom and comment top to fix the error
  // var foo: Foo; 
}

src/index.ts:

globalThis.foo = {
  x: 1
};

console.log(globalThis.foo);

the compile errors on both globalThis.foo accesses. strangely, if i change the let in globals.d.ts to var, it passes. what am i missing?

here's a codesandbox showing the issue: https://codesandbox.io/s/typescript-forked-hm6knw?file=/src/index.ts:0-59

olive adder
#

you shouldbe using var in your declaration files

#

When looking at the code of a global library, you’ll usually see:

  • Top-level var statements or function declarations
#

let variables are scoped and aren't accessible outiside of the scope (outside of the braces in the declare global {})

#

it's tries to match the runtime behavior, so that's why

haughty edge
#

mhmm

olive adder
#

(more about general var vs let in JS)

haughty edge
#

okay, thanks

#

the reason i wasn't sure about using var is because eslint is complaining

#

i could just shut it up but just wondering if this was the right way of doing it

olive adder
#

right, if not properly configured, ESLint thinks it's a regular TS file

#

but it's not

haughty edge
#

ah

#

how do i fix that?

olive adder
#

youcan exclude the .d.ts files

#

don't remember the right property,but it's possible to do that

#

anduse an alternative set of rules for typings files