workers-types icon indicating copy to clipboard operation
workers-types copied to clipboard

Use `WorkerGlobalScope` inside `global` for binding.

Open cosmosgenius opened this issue 5 years ago • 1 comments

The suggested way of accessing env is to create a binding.d.ts file with the following content.

declare global {
  const ENV_KEY: string
}

The problem with this approach is if the env variable is not declared the script just throws at runtime.

A better way would be to extent WorkerGlobalScope like below.

declare global {
  export interface WorkerGlobalScope {
    ENV_KEY: string
  }
}

This way the the env vars are accessed via the self object, thereby have flexibility for error handling and defaults.

cosmosgenius avatar Oct 06 '20 22:10 cosmosgenius

This is a great sugestion . i have been batling with envs in my project for two days now just noticed that bindings file is not working.

mitch1009 avatar Aug 27 '22 07:08 mitch1009

Hey! 👋 Thank you for the suggestion. I don't think we'll go ahead with it though, we'd still uses of bindings in the global scope without a self. prefix to type check. Just putting types on WorkerGlobalScope will prevent this.

mrbbot avatar Oct 21 '22 13:10 mrbbot