Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does typescript not complain about certain undefined variables

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)?
like image 658
flq Avatar asked Dec 19 '16 13:12

flq


People also ask

How do you handle undefined in TypeScript?

To make a variable null we must assign null value to it as by default in typescript unassigned values are termed undefined. We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.

How do you define an undefined variable in TypeScript?

Syntax to declare undefined in TypeScript:var variable_name; Where variable_name is the name of the variable that is declared and is not initialized, thereby making it an undefined variable.

Is undefined true in TypeScript?

Both null & undefined is falsy value in TypeScript. i.e. when we use them in a boolean expression they are coerced to false. But they are neither false nor true.


1 Answers

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:

  • Mdn page on the property
  • Definition in the lib.es6.d.ts

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.

like image 158
Nitzan Tomer Avatar answered Oct 06 '22 01:10

Nitzan Tomer