-1

In the below typescript syntax,

var strToNum: number = window.parseInt("5");

gives error:

tstut.ts(15,31): error TS2551: Property 'parseInt' does not exist on type 'Window'. Did you mean 'parent'?

DOM has,

> window.parseInt
 ƒ parseInt() { [native code] }

Why tsc gives transpilation error?

overexchange
  • 11,586
  • 11
  • 75
  • 203

1 Answers1

0

Window Object does not contain parseInt() definition, so TS is unable to find it there. It's a standard built-in function and should be called by a simple call:

var strToNum: number = parseInt("5");
borkovski
  • 868
  • 8
  • 11
  • 1
    But, `window.parseInt("5")` gives 5 on browser console – overexchange Nov 06 '17 at 08:37
  • parseInt is available on window but should not be used that way because the code would not work in node.js for example . By using window.parseInt you are making code less portable without benefits, Typescript prevents you from making this mistake altogether by marking it as an error. – Walle Cyril Nov 06 '17 at 08:43
  • That's because in HTML, the global scope is the window object. All global variables belong to the window object, but TS doesn't know about it on transpilation time. – borkovski Nov 06 '17 at 08:44
  • @WalleCyril Any name(say `parseInt`) you introduce in `.js` file should be under a scope. `parseInt` looks to be under `window` scope. JavaScript execution model is dictionaries of dictionaries. Any name you introduce in `.js` file becomes a property of a dictionary. – overexchange Nov 06 '17 at 08:45
  • borkovski, you answer is contradicting your comment – overexchange Nov 06 '17 at 08:47
  • I don't see a contradiction. parseInt() is a global function. Global scope = window scope, but not always. TS won't assume it while transpiling, because it's not always right. – borkovski Nov 06 '17 at 09:01
  • What is not alway's right? This is where my question is around. Why TypeScript does not respect `window` scope when typescript is superset of javascript. Any valid javascript code should be accepted by `tsc` – overexchange Nov 06 '17 at 09:10
  • Global scope is not always window object. @WalleCyril gave you an example where it isn't - node.js. That's why Window Object definition does not contain parseInt() function. The same goes for example with console object - it's available in HTML window, but TS won't allow you to call window.console.log(). You can read more about it for example here: https://stackoverflow.com/questions/43627622/what-is-the-global-object-in-nodejs – borkovski Nov 06 '17 at 09:19