w3resource

Exporting Namespace Content in TypeScript

TypeScript Modules and Namespaces : Exercise-8 with Solution

Write a TypeScript namespace called Logger that contains a function logMessage. Export the Logger namespace and import it into a different TypeScript file to use the logMessage function for logging messages.

Sample Solution:

TypeScript Code:

main.ts

import Logger = require('./Logger'); // Import the Logger namespace

Logger.logMessage("This is a log message."); 

Logger.ts

namespace Logger {
  export function logMessage(message: string) {
    console.log('[Info] ${message}');
  }
}

export = Logger; // Export the Logger namespace

Explanation:

In the exercise above -

  • "Logger.ts" is a TypeScript namespace that contains a function "logMessage()". This function logs messages with a "[Info]" prefix to the console.
  • In "main.ts", we import the "Logger" namespace using the 'require' syntax. This is the way to import modules using CommonJS style.
  • Finally, we use the "logMessage()" function from the "Logger" namespace to log a message in the console.

Output:

[Info] This is a log message.

TypeScript Editor:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.


Previous: TypeScript Nested Namespaces.
Next: Merging Declarations in TypeScript - Namespace Example.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/typescript-exercises/typescript-modules-and-namespaces-exercise-8.php