Working with Third-Party Libraries and Type Definitions

1. Welcome and Icebreaker:

  • If you could add any feature to your favorite library, what would it be?

2. Outline the Session:

  • We’ll learn how to use third-party JavaScript libraries in TypeScript and how to install type definitions.
  • Learning Outcomes: Understand how to get type safety when using external libraries.
  • Let’s get typing!

3. Concept Explanation:

  • Many JavaScript libraries don’t include TypeScript types by default.
  • Type definitions are provided via @types packages (DefinitelyTyped) or included in the library.
  • Install types with npm install --save-dev @types/library-name.
  • TypeScript will automatically use these types for type checking and IntelliSense.

4. Live Coding Demonstration:

// Install lodash and its types
// npm install lodash
// npm install --save-dev @types/lodash

import _ from 'lodash';
const arr = [1, 2, 3];
console.log(_.reverse(arr));

// Using a library with no types
declare module 'no-types-lib';
import x from 'no-types-lib';
x.doSomething();

5. Tasks:

  • Short Exercise:
    1. Install a popular library (e.g., axios) and its type definitions.
    2. Import and use the library in a TypeScript file.
    3. Try using a library without types and write a module declaration for it.