Learn TypeScript

Controlling type checking against standard libraries

Controlling type checking against standard libraries

In this lesson, we will learn how to control type checking against standard JavaScript libraries.

Technical requirements

You will need the following installed on your computer for this lesson:

  • Node.js and npm. You can download these from https:/​/​nodejs.​org/​en/​download. If you already have these installed, make sure that Node.js is at least version 8.2, and that npm is at least version 5.

  • Code editor such as Visual Studio Code. This can be installed from https:/​/​code.​visualstudio.​com.

  • The starter project which can be found here.

  • After the starter project has been downloaded. Open it in Visual Studio Code and execute the following command in a Terminal window:

npm install

This will install the project dependency, which is TypeScript.

Understanding the lib option

TypeScript contains types for standard libraries, such as the DOM. TypeScript uses these types when type checking code that interacts with these libraries.

By default, the standard types that are checked depend on the target compilation option. However, this behavior can be changed to a specific list of libraries specified in a lib compilation option.

An example

The starter project uses a compiler option called watch that we haven't used before. Once the compiler is run for the first time, it will automatically run any time any project changes.

The project also contains an index.ts file that uses the new array.flat method.

const flatArr = arr.flat();
  • Run the TypeScript compiler:
npm run tsc

A type error is raised on the flat method call:

Type error

We have target set to ES6 in tsconfig.json which means TypeScript doesn't recognize this array method. This results in it raising a type error.

  • Change target to ESNext in tsconfig.json:
{
"compilerOptions": {
...
"target": "ESNext",
...
},
...
}

The TypeScript compiler is automatically rerun, and the type error is resolved.

This approach might not be feasible though - we might need to target an environment that runs with an older version of ECMAScript.

  • Change target back to ES6.

The type error is raised again after the TypeScript compiler is rerun.

  • Add the following lib option:
{
"compilerOptions": {
...
"lib": ["ESNext", "DOM"]
},
...
}

The type error is resolved after the TypeScript compiler is rerun.

Nice!

All the lib compiler options can be found here.

Summary

The lib option gives fine-grain control over the standard libraries used during TypeScript's type checking. It is useful when you want to target environments that run on old versions of ECMAScript but still use the latest ECMAScript features.

In the next lesson, we will learn how to control the strictness of TypeScripts type checks.

Did you find this lesson useful?

Share this lesson on twitter
© 2024 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more