The tsc
compiler always happily compiles console.log("foo")
. Where is the variable console
declared? The compiler accepts this program even with all lib
s turned off in my tsconfig.json
. So is console
assumed to be universal? What other variables are always declared? More generally, how can I find out what other declarations exist, and where they are coming from? (The only debugging flag I can find is --extendedDiagnostics
, but it seems almost useless.)
A scope is a region of the program and broadly speaking there are three places, where variables can be declared: Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters. Outside of all functions which is called global variables.
Most of the libraries are bundled with a type declaration file of their own in their package distribution, which means once we install a package, we will get all type declaration files inside node_modules/<package-name>/lib . TypeScript uses this and does its magic.
When loading a JavaScript module from “node_modules” TypeScript will look in “node_modules/@types” to see if there is a corresponding type definition for this file. That's where the “@types” scope is special.
TypeScript is distributed with a set of lib.*.d.ts
declaration files which describe the standard library APIs provided by various JavaScript runtimes.
console
is described therein.
The language determines which of these files are applicable based on the --target
option, automatically including them in the compilation context.
For example "target": "es5"
will cause the compiler to include lib.es5.d.ts
in the compilation context.
You can explicitly configure which of these built-in declaration files should be referenced using the --lib
option.
For example "lib": ["es2015", "dom", "dom.iterable"]
.
If you use the navigation features of your IDE, such "go to definition" in Visual Studio Code, will navigate to the to the decoration for console, allowing you to see where it is.
Additional declaration files, such as those provided by various @types
packages, may also contribute potentially overlapping declarations describing JavaScript runtime APIs. This is actually good behavior because it allows packages to describe additional capabilities they provide.
For example @types/node
contains such decorations.
When declared by 3rd party packages, the inclusion of these additional global declaration files is controlled by the --types
option as opposed to the --lib
option.
For example "types": ["node"]
.
The inclusion of these types is not impacted by the --target
option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With