w3resource

TypeScript Named Exports

TypeScript Modules and Namespaces : Exercise-3 with Solution

Write a TypeScript module that exports multiple functions and variables using named exports. Import specific named exports in a separate TypeScript file and use them.

Sample Solution:

TypeScript Code:

main.ts

import { var1, var2, add, greet } from './test_module';

// Use the exported variables and functions
console.log(var1, var2);  
console.log(add(6, 8));  
console.log(greet('Hugleikr Nia')); 

test_module.ts

// Export variables
export const var1 = 'Hello,';
export const var2 = 'TypeScript!';

// Export functions
export function add(a: number, b: number): number {
  return a + b;
}

export function subtract(a: number, b: number): number {
  return a - b;
}

export function greet(name: string): string {
  return `Hello, ${name}!`;
}

Output:

Hello, TypeScript!
14
Hello, Hugleikr Nia!

Run the generated JavaScript file using Node.js:

node main.js

TypeScript Editor:

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


Previous: TypeScript Exporting Classes.
Next: TypeScript Default Export.

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://w3resource.com/typescript-exercises/typescript-modules-and-namespaces-exercise-3.php