0
0
Typescriptprogramming~20 mins

Why declaration files are needed in Typescript - See It in Action

Choose your learning style9 modes available
Why declaration files are needed
📖 Scenario: Imagine you are using a JavaScript library in your TypeScript project. You want to use its functions safely with clear information about what inputs they expect and what outputs they give.
🎯 Goal: You will create a simple TypeScript declaration file to describe a JavaScript function, then use it in your TypeScript code to see how declaration files help with type safety and better coding experience.
📋 What You'll Learn
Create a declaration file with a function signature
Create a TypeScript file that uses the declared function
Show how TypeScript checks types using the declaration file
Print the result of calling the function
💡 Why This Matters
🌍 Real World
Many JavaScript libraries do not have built-in TypeScript types. Declaration files help TypeScript understand these libraries so developers can use them safely.
💼 Career
Knowing how to write and use declaration files is important for TypeScript developers working with existing JavaScript code or third-party libraries.
Progress0 / 4 steps
1
Create a declaration file for a JavaScript function
Create a file named mathUtils.d.ts and declare a function called add that takes two number parameters named a and b, and returns a number.
Typescript
Need a hint?

Use the declare function syntax to describe the function signature without implementation.

2
Create a TypeScript file that uses the declared function
Create a file named app.ts and write code that calls the add function with arguments 5 and 7, and stores the result in a variable called sum.
Typescript
Need a hint?

Use const sum = add(5, 7); to call the function and save the result.

3
Add a type check by trying to call the function with wrong types
In app.ts, add a line that calls add with arguments "hello" and 10. This should cause a type error because the first argument is not a number.
Typescript
Need a hint?

Try calling add with a string and a number to see how TypeScript warns about wrong types.

4
Print the result of the correct function call
Add a console.log statement to print the value of sum.
Typescript
Need a hint?

Use console.log(sum); to show the result.