Skip to content

Add feature to re-declare variable #37771

Open
@dguttman-jacada

Description

@dguttman-jacada

Search Terms

redeclare variable, re-declare variable, augment variable, merge variable declaration, declaration override

Suggestion

define a redeclare keyword which allows re-declaration of a typed variable.
e.g.

redeclare var foo: {
  prop: string
};

Use Cases

When an external library declares a variable, e.g.

declare var x: {
  prop: string;
};

The redeclare keyword can be used somewhere else to override the declaration:

redeclare var x: number;

or augment it:

redeclare var x: typeof x & {
  augmentedProp: number;
}

This would allow to type the pure JavaScript case of:

// lib.js
var x = {
  prop: "foo"
};

// app.js
x.augmentedProp = 10;

console.log(x.prop, x.augmentedProp);

Examples

declare var URLSearchParams: {
    prototype: URLSearchParams;
    new(init?: string[][] | Record<string, string> | string | URLSearchParams): URLSearchParams;
    toString(): string;
};

defined in lib.dom.d.ts

to extend the variable with additional static methods to URLSearchParams is not possible currently (see here).

The feature can be used in the following way:

redeclare var URLSearchParams: typeof URLSearchParams & {
  fromObject(obj: object): URLSearchParams;
};

if (!URLSearchParams.fromObject) {
  URLSearchParams.fromObject = function(obj: object): URLSearchParams { /* implementation */  }
}

Checklist

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. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions