typescript compiler options: lib vs. target

2020-04-08

 | 

~3 min read

 | 

423 words

I was setting up a new typescript project the other day when I realized that there were two compiler options that felt very similar: lib and target.

According to the Typescript Compiler Options docs, the purpose of the options are:

  • lib is used to list “library files to be included in the compilation”
  • target is used to “specify [the] ECMAScript target version”

Reading those definitions didn’t exactly clarify how or why I would use one or the other - or both.

After finding this conversation on Stack Overflow, however, I feel better equipped thanks to Aaron Bell’s answer.

The reason Typescript has both is historic. target was always there, while lib was added later.

This was done to handle the evolution of Javascript with new features like Promises.

For example, before lib was available, if you wanted to serve users that were still on ES5, you had two choices:

  1. Do not use features introduced in newer versions, or
  2. Target the most modern version of Javascript needed, and then use a transpiler like Babel to compile down to the appropriate level later

The introduction of lib solves that problem by allowing the lib and target to diverge - avoiding compiler errors by referencing a more modern type declaration file (via lib) while still compiling down to the targeted version.

So, what are the different options for target and why would you use them? The target ultimately controls the bundle size (unless you’re using another too like Babel as well). So, the further back you go, the larger the bundle will likely be as Typescript will provide “down level language helpers”, though not any polyfills. The lib option on the other hand helps with the compiler check ensuring that your type hints match what you’re expecting at runtime.

The reason to use an older JS version then is accessibility. Not every user who wants to use your application will have the latest browser versions. Webhint.io illustrates the point nicely:

TARGET CHROME EDGE FIREFOX INTERNET EXPLORER SAFARI
ES3
ES5 5 4 9 5
ES2015 49 13 37 10
ES2016 57 14 52 10.1
ES2017 58 16 53 10.1

Related Posts
  • Typescript: TSLib versions and Spreading Arrays


  • Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!