Practice: Create a Small Library with Modules and Type Definitions

1. Welcome and Icebreaker:

  • If you could create a library for any purpose, what would it do?

2. Outline the Session:

  • We’ll practice creating a small TypeScript library with modules and type definitions.
  • Learning Outcomes: Apply module and type definition concepts to build a reusable library.
  • Let’s build something useful!

3. Concept Explanation:

  • Building your own library helps you understand how modules and type definitions work together.
  • We’ll create a simple math library as an example.
  • The key is to export functions and provide type definitions for users.

4. Live Coding Demonstration:

// mathUtils.ts
export function add(a: number, b: number): number {
  return a + b;
}
export function multiply(a: number, b: number): number {
  return a * b;
}

// mathUtils.d.ts
declare module './mathUtils' {
  export function add(a: number, b: number): number;
  export function multiply(a: number, b: number): number;
}

// app.ts
import { add, multiply } from './mathUtils';
console.log(add(2, 3));
console.log(multiply(4, 5));

5. Tasks:

  • Short Exercise:
    1. Create a module file with two functions and export them.
    2. Write a declaration file for your module.
    3. Import and use your functions in another file.
    4. Try using your library in a new TypeScript project.