0
0
Typescriptprogramming~15 mins

Callback function types in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Callback function types
📖 Scenario: You are building a simple event handler system where functions are called back when an event happens.
🎯 Goal: Create a callback function type, use it to type a function parameter, and call the callback with a message.
📋 What You'll Learn
Create a callback type named Callback that accepts a single string parameter and returns void.
Create a function named triggerEvent that takes a message of type string and a callback of type Callback.
Inside triggerEvent, call the callback with the message.
Call triggerEvent with the message 'Hello, TypeScript!' and a callback that prints the message.
💡 Why This Matters
🌍 Real World
Callbacks are used in many programs to run code after something happens, like a button click or data loading.
💼 Career
Understanding callback types helps you write safer and clearer TypeScript code, which is important for frontend and backend development.
Progress0 / 4 steps
1
Create the callback type
Create a type alias called Callback for a function that takes a single string parameter named msg and returns void.
Typescript
Need a hint?

Use type Callback = (msg: string) => void; to define the callback type.

2
Create the triggerEvent function
Create a function named triggerEvent that takes two parameters: message of type string and callback of type Callback.
Typescript
Need a hint?

Define triggerEvent with parameters message: string and callback: Callback. Inside, call callback(message);.

3
Call triggerEvent with a callback
Call the function triggerEvent with the message 'Hello, TypeScript!' and a callback function that takes a parameter msg and prints it using console.log(msg).
Typescript
Need a hint?

Call triggerEvent with the string and an arrow function that logs the message.

4
Display the output
Run the program and print the output to show the message Hello, TypeScript!.
Typescript
Need a hint?

Run the code to see the message printed in the console.