0
0
Typescriptprogramming~30 mins

Writing custom declaration files in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Writing custom declaration files
📖 Scenario: You are using a JavaScript library called mathTools in your TypeScript project. This library does not have built-in TypeScript support, so you want to create a custom declaration file to help TypeScript understand the library's functions and types.
🎯 Goal: Create a custom declaration file mathTools.d.ts that describes the add and multiply functions of the mathTools library, then use these functions in a TypeScript file with proper type checking.
📋 What You'll Learn
Create a declaration file named mathTools.d.ts with the correct module and function declarations.
Declare two functions: add and multiply, each accepting two numbers and returning a number.
Import and use these functions in a TypeScript file named app.ts.
Print the results of calling add(5, 3) and multiply(4, 7).
💡 Why This Matters
🌍 Real World
Many JavaScript libraries do not come with TypeScript types. Writing custom declaration files helps you use these libraries safely in TypeScript projects.
💼 Career
Understanding how to write declaration files is important for TypeScript developers working with third-party JavaScript code or legacy libraries without type support.
Progress0 / 4 steps
1
Create the declaration file with module and function signatures
Create a file named mathTools.d.ts and declare a module called "mathTools". Inside it, declare two functions: add and multiply. Both functions should accept two parameters named a and b of type number and return a number.
Typescript
Need a hint?

Use declare module "mathTools" { ... } to describe the external library module. Inside, declare the functions with their parameter and return types.

2
Import the functions from the custom declaration file
In a new file named app.ts, import the add and multiply functions from the "mathTools" module using ES module syntax.
Typescript
Need a hint?

Use import { add, multiply } from "mathTools"; to import the declared functions.

3
Use the imported functions to calculate values
In app.ts, create two variables: sum that stores the result of add(5, 3) and product that stores the result of multiply(4, 7).
Typescript
Need a hint?

Call the imported functions with the specified arguments and assign the results to variables.

4
Print the results to the console
Add two console.log statements in app.ts to print the values of sum and product.
Typescript
Need a hint?

Use console.log(sum); and console.log(product); to display the results.