Skip to content

Allow declaration declare within conditionals #25570

Closed
@ganeshkbhat

Description

@ganeshkbhat

Search Terms

declare and variable declaration (for issues)

Suggestion

Allow declaration inside conditionals like below:

if (conditional) {
     declare var variable: any | <T>
} 

Use Cases

Lets take an example of Web Worker support from browser. If the Web Worker (window.Worker) is not available I will switch to a polyfill that creates a window.PseudoWorker object option. The pseudoworker is always loaded irrespective of browser support.

In my .ts class, I will create the following:

declare var Worker: Worker | undefined;
if (!Worker) {
     declare var PseudoWorker: any; // this fails
}

class y {
  worker: any;
  constructor() {
    if (!Worker) {
         this.worker = new PseudoWorker('myurl.js');
    } else {
         this.worker = new Worker('myurl.js');
    }
  }
}

An alternative way to approach the following is:

declare var PseudoWorker: Worker | any;

But the issue with this is, I am loading a polyfill with PseudoWorker all the time in the global context irrespective of the fact that Web Worker is supported or not (window.Worker object present or not). Since the Object is always going to be available there is a clash in the object names used.

This is however different from the #23602 issue by the way that:

  • The declaration in the global context stays for pseudoworker and worker for supported browsers OR just pseudoworker for unsupported browsers
  • The declaration of pseudoworker object to be used inside .ts file module should be optional based on presence of an object based on browser support
  • There will be global naming issues (unexpected overriding) if the conditional declaration is not there (incase of pseudoworker when the browser worker support or window.Worker object is available)

An alternate recommendation based on the 23602 issue may be

declare? (var Worker: Worker) : (var PseudoWorker: any); (updated from declare? var Worker: Worker || var PseudoWorker: any;)

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. new expression-level syntax)

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions