TypeScript: js with window object fails to compile

TypeScript Version: Version 2.0.0

Code

// from https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
function storageAvailable(type) {
    try {
        var storage = window[type],
            x = '__storage_test__';
        storage.setItem(x, x);
        storage.removeItem(x);
        return true;
    }
    catch(e) {
        return false;
    }
}

Expected behavior: This is a snippet of code from: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API

Since this is sample javascript code, I was expecting it to work.

Actual behavior: var storage gets typed as Window, and thus can’t resolve setItem nor removeItem.

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 18 (11 by maintainers)

Most upvoted comments

i do not think there is something wrong with the snippet per se. the issue here is the DOM spec says that indexing into the window object with a number returns you a frame, in the snippet, the TS compiler does not know what is the type of type would be at run time, so it is safe to assume it can be a number, @yortus’ suggession in https://github.com/Microsoft/TypeScript/issues/10457#issuecomment-241240834 is the ideal workaround here.

My proposal is to remove the index signature all together. I would expect ppl indexing into window with any more than indexing into it with number to get frames.