Modules & Namespaces Interview Questions
Comprehensive modules & namespaces interview questions and answers for TypeScript. Prepare for your next job interview with expert guidance.
Questions Overview
1. What are ES modules in TypeScript and how do they differ from namespaces?
Basic2. How do you use export and import statements in TypeScript?
Basic3. What are namespaces in TypeScript and when should you use them?
Moderate4. How do you use barrel exports in TypeScript?
Moderate5. What is module augmentation in TypeScript?
Advanced6. How do you handle circular dependencies in TypeScript modules?
Advanced7. What are ambient modules in TypeScript?
Advanced8. How do you use namespace merging in TypeScript?
Moderate9. What are the different module resolution strategies in TypeScript?
Advanced10. How do you use dynamic imports in TypeScript?
Moderate11. What are declaration files (.d.ts) and how do they work with modules?
Advanced12. How do you use re-exports in TypeScript modules?
Moderate13. What are the best practices for organizing modules in TypeScript?
Moderate14. How do you handle module path aliases in TypeScript?
Moderate15. What is the difference between internal and external modules?
Basic16. How do you use namespace exports and imports?
Moderate17. What are synthetic default imports in TypeScript?
Advanced18. How do you handle module side effects in TypeScript?
Advanced19. What are global modules in TypeScript?
Advanced20. How do you use type-only imports and exports?
Moderate21. What are the patterns for lazy loading modules in TypeScript?
Advanced22. How do you handle module resolution in monorepos?
Advanced23. What are the different ways to handle module augmentation?
Advanced24. How do you handle module resolution fallbacks?
Advanced1. What are ES modules in TypeScript and how do they differ from namespaces?
BasicES modules are the standard JavaScript module system that TypeScript supports. They use import/export syntax and provide better code organization and dependency management. Unlike namespaces (internal modules), ES modules are file-based, support better tree-shaking, and are the preferred way to organize code. Example: export class MyClass {} and import { MyClass } from './myModule';
2. How do you use export and import statements in TypeScript?
BasicTypeScript supports various export/import syntaxes: 1) Named exports: export { MyClass }; 2) Default exports: export default MyClass; 3) Import named: import { MyClass } from './module'; 4) Import default: import MyClass from './module'; 5) Import all: import * as module from './module'. Each type serves different purposes in module organization.
3. What are namespaces in TypeScript and when should you use them?
ModerateNamespaces (formerly 'internal modules') are TypeScript's own module system for encapsulating code. They use the namespace keyword and are useful for avoiding name collisions in global scope. Example: namespace Mathematics { export function add(x: number, y: number): number { return x + y; } }. However, ES modules are generally preferred for modern applications.
4. How do you use barrel exports in TypeScript?
ModerateBarrel exports consolidate multiple exports into a single entry point using an index.ts file. Example: export * from './math'; export * from './string'; export * from './array';. This simplifies imports by providing a single import point and helps manage large codebases by organizing related functionality.
5. What is module augmentation in TypeScript?
AdvancedModule augmentation allows you to add new declarations to existing modules. Example: declare module 'lodash' { interface LoDashStatic { myCustomFunction(arg: string): number; } }. This is useful for adding type definitions to existing JavaScript modules or extending third-party module declarations.
6. How do you handle circular dependencies in TypeScript modules?
AdvancedCircular dependencies occur when two modules import each other. They can be resolved by: 1) Restructuring code to avoid circularity, 2) Using interfaces instead of concrete implementations, 3) Moving shared code to a separate module, 4) Using import type for type-only imports. Example: import type { User } from './user' instead of import { User } from './user'.
7. What are ambient modules in TypeScript?
AdvancedAmbient modules declare types for JavaScript modules that don't have TypeScript declarations. They use declare module syntax. Example: declare module 'my-library' { export function doSomething(): void; }. They're commonly used in .d.ts files to provide type information for JavaScript libraries.
8. How do you use namespace merging in TypeScript?
ModerateNamespace merging allows combining multiple namespace declarations with the same name. Example: namespace Animals { export class Dog {} } namespace Animals { export class Cat {} }. This creates a single namespace containing both Dog and Cat classes. It's similar to interface merging but for namespaces.
9. What are the different module resolution strategies in TypeScript?
AdvancedTypeScript supports several module resolution strategies: 1) Classic: Legacy resolution for AMD/System.js, 2) Node: Follows Node.js module resolution, 3) baseUrl: Resolves modules relative to a base directory, 4) paths: Allows custom module path mapping. These are configured in tsconfig.json using the moduleResolution option.
10. How do you use dynamic imports in TypeScript?
ModerateDynamic imports allow loading modules on demand using import() syntax. Example: async function loadModule() { const module = await import('./myModule'); module.doSomething(); }. This enables code-splitting and lazy loading of modules for better performance.
11. What are declaration files (.d.ts) and how do they work with modules?
AdvancedDeclaration files (.d.ts) contain type information for JavaScript modules. They define the shape of modules without implementation details. Example: declare module 'my-module' { export interface Config { debug: boolean; } export function initialize(config: Config): void; }. They enable TypeScript to understand external JavaScript libraries.
12. How do you use re-exports in TypeScript modules?
ModerateRe-exports allow you to export items from other modules. Syntax includes: export { Something } from './other', export * from './other', and export { Something as OtherThing } from './other'. This helps create clean public APIs and organize code hierarchy.
13. What are the best practices for organizing modules in TypeScript?
ModerateBest practices include: 1) One class/feature per file, 2) Use barrel exports (index.ts) for related features, 3) Keep modules small and focused, 4) Use meaningful file names matching exported content, 5) Group related functionality in directories, 6) Use clear import paths, 7) Avoid circular dependencies. This improves code maintainability and readability.
14. How do you handle module path aliases in TypeScript?
ModerateModule path aliases are configured in tsconfig.json using the paths option. Example: { 'compilerOptions': { 'baseUrl': '.', 'paths': { '@app/*': ['src/app/*'] } } }. This allows using @app/feature instead of relative paths, making imports cleaner and more maintainable.
15. What is the difference between internal and external modules?
BasicInternal modules (namespaces) use the namespace keyword and are TypeScript-specific. External modules (ES modules) use import/export syntax and are the standard JavaScript module system. Example: namespace MyNamespace {} vs. export class MyClass {}. ES modules are preferred for modern applications.
16. How do you use namespace exports and imports?
ModerateNamespaces use export keyword for public members and can be accessed using dot notation. Example: namespace Math { export function add(x: number, y: number): number { return x + y; } } Usage: Math.add(1, 2). For cross-file namespaces, use /// <reference path='./math.ts' /> syntax.
17. What are synthetic default imports in TypeScript?
AdvancedSynthetic default imports allow importing modules that don't have explicit default exports as if they did. Controlled by esModuleInterop compiler option. Example: import React from 'react' works even if React uses module.exports = React. This improves compatibility with CommonJS modules.
18. How do you handle module side effects in TypeScript?
AdvancedModule side effects are handled using import statements without bindings. Example: import './polyfills'; This executes the module code without importing any values. It's useful for polyfills, global styles, or other code that needs to run during module initialization.
19. What are global modules in TypeScript?
AdvancedGlobal modules are ambient modules that add types to the global scope. Example: declare global { interface Window { myCustomProperty: string; } }. They're useful for extending global objects or declaring global variables, but should be used sparingly to avoid polluting global namespace.
20. How do you use type-only imports and exports?
ModerateType-only imports/exports are used for importing/exporting types without value emissions. Syntax: import type { MyType } from './types'; export type { MyType }. This helps reduce bundle size by removing type information during compilation while maintaining type safety.
21. What are the patterns for lazy loading modules in TypeScript?
AdvancedLazy loading patterns include: 1) Dynamic imports: import('./module'), 2) Route-based splitting: loadChildren in Angular routes, 3) Component-based splitting in React.lazy(). Example: const MyComponent = React.lazy(() => import('./MyComponent')). This improves initial load time by loading modules on demand.
22. How do you handle module resolution in monorepos?
AdvancedMonorepo module resolution involves: 1) Using project references in tsconfig.json, 2) Configuring path aliases for packages, 3) Setting up proper build order, 4) Managing shared dependencies. Example: { 'references': [{ 'path': '../common' }], 'paths': { '@org/*': ['packages/*/src'] } }.
23. What are the different ways to handle module augmentation?
AdvancedModule augmentation can be done through: 1) Declaration merging: declare module 'module' {}, 2) Global augmentation: declare global {}, 3) Namespace augmentation: namespace NS {}. Example: declare module 'express-session' { interface SessionData { userId: string; } }
24. How do you handle module resolution fallbacks?
AdvancedModule resolution fallbacks are configured through: 1) moduleResolution in tsconfig.json, 2) baseUrl and paths for custom mappings, 3) TypeScript path mapping patterns like * and **. Example: { 'paths': { '*': ['node_modules/*', 'fallback/*'] } }. This helps handle different module formats and locations.