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:


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

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


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

export = Logger; // Export the Logger namespace


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.


[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.

Follow us on Facebook and Twitter for latest update.