microsoft/TypeScript

Augmenting the global scope in a module - Able to reference the augmentation when it is not referenced causing runtime error.

Saulzi opened this issue · 1 comments

TypeScript Version: 2.2.1

When using AMD as module type.

If I augment the global scope as per below

extension.ts

declare global {
    interface Array<T> {
        SomeMethod() : void;
    }
}

Array.prototype.SomeMethod = () => { /* Some Code */  }

export = "Something"

The augmentation is available allthough I have not referenced it so the following will compile.

user.ts

var T = [];
T.SomeMethod();

This will cause a runtime error i.e. SomeMethod has not been defined whereas if i do the following.

user.ts

import "extension"

var T = [];
T.SomeMethod();

will work as the js generated (define(["require", "exports", "extension"]) will load the augmentation in.

I cannot see any way of saying that the augmentation will only be available when the module is imported in https://www.typescriptlang.org/docs/handbook/declaration-merging.html.

it would be nice to be able to do something like the following

export declare global     // This means we dont need to export something else in the file
{
     interface Array<T> {
        SomeMethod() : void;
    }
}

If we dont import the augmentation when we are using it it will be a compiler error.

The declaration of Array and so is the augmentation are in the global scope; they are visible throughout the compilation. the compiler can not tell when they are applied or not.