0
0
Typescriptprogramming~15 mins

Ambient declarations in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Ambient Declarations in TypeScript
📖 Scenario: You are building a TypeScript project that uses a JavaScript library called mathLib. This library is loaded separately and provides a function to calculate the square of a number. Since TypeScript does not know about this library by default, you need to tell TypeScript about it using ambient declarations.
🎯 Goal: Learn how to create an ambient declaration for an external JavaScript function and use it safely in TypeScript.
📋 What You'll Learn
Create an ambient declaration for the external function square.
Use the declared square function in TypeScript code.
Print the result of calling square with a number.
💡 Why This Matters
🌍 Real World
Ambient declarations help TypeScript understand code from external JavaScript libraries that do not have type information.
💼 Career
Many real-world projects use third-party JavaScript libraries. Knowing how to write ambient declarations lets you safely use these libraries in TypeScript.
Progress0 / 4 steps
1
Create an ambient declaration for the square function
Write an ambient declaration for a function called square that takes a number and returns a number. Use the declare keyword.
Typescript
Need a hint?

Use declare function followed by the function name and its type signature.

2
Create a variable to hold a number to square
Create a variable called num and set it to the number 5.
Typescript
Need a hint?

Use let num = 5; to create the variable.

3
Call the ambient square function with num
Create a variable called result and set it to the value returned by calling square(num).
Typescript
Need a hint?

Use let result = square(num); to call the function and store the result.

4
Print the result to the console
Write a console.log statement to print the value of result.
Typescript
Need a hint?

Use console.log(result); to display the output.