#Simplifying Declare Global

14 messages · Page 1 of 1 (latest)

hollow anchor
#

Any way to simplify the global declarations in the following code? Or alternative ways to make foo/etc global?

declare global {
    const foo: typeof lib['foo']
    const bar: typeof lib['bar']
    const baz: typeof lib['baz']
    // ...
}

const lib = {
    foo,
    bar,
    baz,
    // ...
}

Object.assign(global, lib)
ashen compass
#
type Lib = typeof lib;
declare global {
  [P in keyof Lib]: Lib[P];
}
#

Also why you need then to be global?

hollow anchor
#

I don't think that works?

#

As for why, I'm doing some unconventional stuffs and adding them to global is easier for the consumer of my library.

ashen compass
manic pecan
agile quarryBOT
#
Gerrit0#7591

Preview:```ts
type Lib = typeof lib;
declare global {
[P in keyof Lib]: Lib[P];
}

const lib = { a: 1, b: "" }

globalThis.a;

export {}```

hollow anchor
#

Yeah declare global is not an object expression, it's a block statement.

#

I was thinking there's an interface for globalThis that I could declaration merge into, but the few ones I've tried didn't seem to work.

#

This is for Node.js btw, if that changes things.

zenith wasp
#

would it be easy enough for consumers of your library to access them under a single root object? if so you could do this:

declare global {
  const stuff: typeof lib
}

and users can do stuff.foo. that might be better in terms of minimizing global namespace pollution anyway

(but there's a good chance you already considered this and ruled it out)

hollow anchor
#

Yeah considered and decided against it.

#

I guess it's not possible then, but it's also not a huge deal I can just do it manually.