Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a global `name` variable declared in typescript and can I avoid using it?

A friend refactored some code and moved the definition of a variable called name from the function's top-level scope into a then's body. This variable was used in a subsequent then which caused a ReferenceError since name was not in scope.

We couldn't understand how the code passed compilation until we saw that typescript/lib.d.ts has the following deceleration:

declare const name: never;

Long story short, I have two questions.

  1. Why is name (as well as length and many other globals) added by default to typescript?
  2. From the surrounding code this seems meant for projects intended to run in a browser, we're a node.js project. Can we opt out from having these declarations added for us?
like image 826
Motti Avatar asked Apr 24 '17 10:04

Motti


People also ask

Should you avoid global variables?

Using global variables causes namespace pollution. This may lead to unnecessarily reassigning a global value. Testing in programs using global variables can be a huge pain as it is difficult to decouple them when testing.

What does declare global do in TypeScript?

To declare a global variable in TypeScript, create a . d. ts file and use declare global{} to extend the global object with typings for the necessary properties or methods.

Is it bad practice to use global variables in JavaScript?

Avoid globals. Global variables and function names are an incredibly bad idea. The reason is that every JavaScript file included in the page runs in the same scope.

Are global variables bad practice?

Non-const global variables are evil because their value can be changed by any function. Using global variables reduces the modularity and flexibility of the program. It is suggested not to use global variables in the program. Instead of using global variables, use local variables in the program.


1 Answers

This seems to be a very old browser behaviour. Referring to the MDN both name and length are properties of the window object.

  • https://developer.mozilla.org/en-US/docs/Web/API/Window/name
  • https://developer.mozilla.org/en-US/docs/Web/API/Window/length

In order to get rid of all the DOM-specific declarations, you can set the lib property in your tsconfig accordingly. You cann see all options on this page. Take a look at the --lib flag.

An option to tell TypeScript your code runs on Node.JS would be nice. But it seems not yet implemented: https://github.com/Microsoft/TypeScript/issues/9466

like image 72
Sebastian Sebald Avatar answered Sep 28 '22 09:09

Sebastian Sebald