Search code examples
typescript

What does the TypeScript "lib" option really do?


I have still not been able to find good answer for this. The "target" option defines, what version of Javascript the result will run on. The "lib" option is less clearly described anywhere. Seems like it is a more granular way to describe the target environment, but then it seems strange it affects what you can write in the .ts source files. Thought TS what as superset of JS, so why does it affect whether, e.g., Promise() is available or not? This seems like it does not only define the target but also affect what functions you have available in Typescript.

Can someone explain that clearly or direct to an answer (there is none at typescriptlang.org or in the books I have looked at). For instance "Specify library files to be included in the compilation", which explains absolutely nothing.


Solution

  • Typescript does not have any built-in types all types come from a set of base definitions (located in the lib folder in the typescript install directory). By default the target defines which libs are included. For example the docs state:

    Note: If --lib is not specified a default list of librares are injected. The default libraries injected are:

    ► For --target ES5: DOM,ES5,ScriptHost

    ► For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost

    The basic idea is that while target is deals with language features (more specifically which language features need to be down compiled, ex: for-of, or arrow functions), the lib option deals with what facilities the runtime environment has (ie. what built-in objects look like, what they are).

    Ideally the default libs for a given target should be used. We may, however, have an environment which supports some of the runtime facilities but not the language features, or we may target runtime with a lower es version and poly-fill some of the runtime facilities, which can be in general done for some things (ex: Promises).