#how to `declare` global vars like `process` for Multi platform purpose?

27 messages · Page 1 of 1 (latest)

still perch
#

demo codes:

const cwd = (()=>{
  if(typeof Deno !== 'undefined') return Deno.cwd();
  if(typeof process !== 'undefined') return process.cwd();
  if(typeof location !== 'undefined') return location.href;
  return '';
})()

error: Cannot find name 'process'. deno-ts(2580)


tried:

declare global {
  const Deno: { cwd: () => string };
  const process: { cwd: () => string };
  const location: { href: string };
}

error: Cannot redeclare block-scoped variable 'Deno'.deno-ts(2451)


What I want to do:

  • when Deno exist in type scope:
    • do nothing on Deno
  • when Deno doesn't exist:
    • Declare it
  • repeat this on process and location
still perch
#

!helper

copper raptor
#

Use a type assertion

#

To tell Ts that the variable may exist

#
declare global {
  interface Window {
    Deno?: { cwd: () => string };
    process?: { cwd: () => string };
    location?: { href: string };
  }
}

const cwd = (() => {
  if (typeof Deno !== 'undefined') return Deno.cwd();
  if (typeof process !== 'undefined') return process.cwd();
  if (typeof location !== 'undefined') return location.href;
  return '';
})();``` 

This tells ts that deno location and variable may exist but it's optional
fair dust
#

there's no type assertion there, btw.

sick gazelle
#

The "cannot redeclare Deno" error probably means you already have Deno types included so it doesn't allow you to declare it again.

#

Not sure how Deno works, but an easy solution is to just remove Deno types and declare them as optional.

#

UnJS packages work for all runtimes, you can use them as a reference to see how they do their types.

still perch
#

seems like it's not a part of syntax

still perch
still perch
#

But I need it

#

I just want to introduce it when it's undef

sick gazelle
#

Well you can't change an existing type.

still perch
#

but not affecting when it's already there

#

Conditional

#

I mean conditional

#

not change it when exist
only when it's undef

#

in some env it's not a existing type

#

but in other it exist

#

Inconsistency between envs is the problem

#

I need a Fallback to cancel inconsistencies

#

!helper

vagrant hatch