7

I have the following example:

class Uncle {
  constructor(public name : string) { }

  talk() {
    return "Hello my name is " + name;
  }
}

let p : Uncle = new Uncle("Jo");
console.log(p.talk());

For certain variable names, typescript (right now Version 2.1.4) will not complain that they are not defined in your program (In the method talk, name is being used without this.). name is one of those.

If I rename the variable to, say, firstName, the compiler complains rightfully...

error TS2663: Cannot find name 'firstName'. Did you mean the instance member 'this.firstName'?

Same goes for e.g. window, which is apparently assumed to exist.

My question(s) are:

  • Which variable names are assumed to exist and why?
  • Can that behaviour be changed (e.g. in some linters you can state which variables you expect to be globally available)?
Shreya Shetty
  • 133
  • 1
  • 9
flq
  • 22,247
  • 8
  • 55
  • 77

1 Answers1

5

The reason it won't complain about name is that there's a variable called name in the global namespace.
Open the console in the developer tools and write name and press enter and you'll receive: "".

More resources:

All global variables can be used without defining them.

In order to remove all global definitions you can, e.g. in your tsconfig.json, set the "libs" option to an empty array. This will remove all globals.

flq
  • 22,247
  • 8
  • 55
  • 77
Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
  • Do you know if there is a way to turn this off? – flq Dec 19 '16 at 13:35
  • Turn what off? The variable `name` exists, what would you like the compiler to do? – Nitzan Tomer Dec 19 '16 at 13:42
  • not necessarily e.g. when you write code for a node.js application, window and friends wouldn't exist. In such a case it would be nice if the compiler wouldn't assume the existence of those globals. – flq Dec 19 '16 at 14:14
  • Well, I guess that you can play around with the `--lib` compiler option and get to a configuration which doesn't include `name` (or other declarations) here's the [list of libs](https://github.com/Microsoft/TypeScript/tree/master/lib), I haven't tried it and haven't searched in which lib it's included, but in theory it might be done. But that seems like an over kill to me. – Nitzan Tomer Dec 19 '16 at 14:28