Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Declaring a global array extension leads to compiler error #26660

Closed
matthiasburger opened this issue Aug 24, 2018 · 2 comments
Closed

Declaring a global array extension leads to compiler error #26660

matthiasburger opened this issue Aug 24, 2018 · 2 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@matthiasburger
Copy link

I want to write that array-extension in TypeScript:

if (!Array.prototype.remove) {
    Array.prototype.remove = function <T>(elem: T): T[] {
        return this.filter(e => e !== elem);
    }
}

so I need to declare an interface for it. There's nothing in that file, just:

declare global {
    interface Array<T> {
        remove(elem: T): Array<T>;
    }
}

but the compiler cries:

TS2669: Augumentations for the global scope can only be directly nested in external modules or ambient module declarations

funny is, when I add this line before:

import * as $ from "jquery";

(what has nothing to do with the Array or something - jQuery is not used here), it's okay for the compiler.

What's going on here?

@AlCalzone
Copy link
Contributor

What's going on here?

https://www.typescriptlang.org/docs/handbook/modules.html
In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).

After adding the import, your file gets treated as a module - and therefore the global scope augmentation is okay. If you leave out the declare global, you automatically augment the global scope:

// file: array.d.ts
interface Array<T> {
	remove(elem: T): Array<T>;
}

// another file:
[].remove(undefined); // works!

@matthiasburger
Copy link
Author

@AlCalzone (nice name!)
...damn... it works. thank you!! should've read the handbook better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

3 participants