*** 1. Explain Generics in TypeScript

Generics allow you to create reusable, flexible, and type-safe components in TypeScript.

Instead of working with a specific data type, generics allow functions, classes, and interfaces to work with multiple types while preserving type safety.

Why Generics Are Important

  • Reusability
  • Type safety
  • Better IntelliSense support
  • Avoids using any

Without Generics

function identity(value: any): any {
return value;
}

Problem:

  • Loses type safety
  • TypeScript cannot predict returned type

With Generics

function identity<T>(value: T): T {
return value;
}

let num = identity<number>(10);
let str = identity<string>("Hello");

Explanation

  • T is a type parameter
  • It acts like a placeholder for a data type

Interview Insight

Interviewers often ask:

  • Why use generics instead of any?
  • Difference between generics and union types
  • Real-world use in APIs, reusable utilities, React components

*** 2. What are Generic Classes / Functions / Interfaces?

Generics can be used with:

  • Functions
  • Classes
  • Interfaces

1. Generic Function

function getData<T>(value: T): T {
return value;
}

Usage

getData<string>("TypeScript");
getData<number>(100);

2. Generic Class

class Box<T> {
value: T;

constructor(value: T) {
this.value = value;
}

getValue(): T {
return this.value;
}
}

const numberBox = new Box<number>(10);

Use Case

Useful for:

  • Data structures
  • Services
  • Repository patterns

3. Generic Interface

interface ApiResponse<T> {
data: T;
success: boolean;
}

Usage

const response: ApiResponse<string> = {
data: "Success",
success: true
};

Interview Tip

Generic interfaces are commonly used in:

  • API responses
  • Axios responses
  • Redux actions
  • React props

** 3. What are Decorators in TypeScript?

Decorators are special functions that add metadata or modify classes, methods, properties, or parameters.

They are widely used in:

  • Angular
  • NestJS
  • Dependency Injection systems

Decorator Syntax

Decorators use the @ symbol.

Example

function Logger(constructor: Function) {
console.log("Class Created");
}

@Logger
class User {
}

Types of Decorators

  1. Class Decorator
  2. Method Decorator
  3. Property Decorator
  4. Parameter Decorator
  5. Accessor Decorator

Real-World Example

@Component({
selector: 'app-root'
})
class AppComponent {
}

Interview Insight

Decorators are heavily asked in:

  • Angular interviews
  • NestJS backend interviews

*** 4. How do you enable decorators in TypeScript?

Decorators are experimental features.

You must enable them in tsconfig.json.

Configuration

{
"compilerOptions": {
"experimentalDecorators": true
}
}

Optional Metadata Support

{
"emitDecoratorMetadata": true
}

Installation (Common in Frameworks)

npm install reflect-metadata

Import

import "reflect-metadata";

Interview Tip

Common follow-up:

  • Why are decorators experimental?
  • What is reflection metadata?

** 5. What are Mixins in TypeScript?

Mixins allow combining multiple classes/features into one class.

TypeScript does not support multiple inheritance directly, but mixins provide similar behavior.

Example

class CanRun {
run() {
console.log("Running");
}
}

class CanEat {
eat() {
console.log("Eating");
}
}

class Person implements CanRun, CanEat {
run!: () => void;
eat!: () => void;
}

applyMixins(Person, [CanRun, CanEat]);

function applyMixins(derivedCtor: any, constructors: any[]) {
constructors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype)
.forEach(name => {
derivedCtor.prototype[name] =
baseCtor.prototype[name];
});
});
}

Advantages

  • Code reuse
  • Flexible architecture
  • Avoids deep inheritance

Interview Insight

Mixins are commonly discussed in:

  • Advanced TypeScript interviews
  • Framework architecture discussions

*** 6. What is a TypeScript Definition File (.d.ts)?

A .d.ts file contains only type declarations, not actual implementation.

It helps TypeScript understand the types of JavaScript libraries.

Example

declare function greet(name: string): void;

Common Usage

Used for:

  • JavaScript libraries
  • Third-party packages
  • Global variables

Example

lodash.d.ts
jquery.d.ts

Why Important?

Without definition files:

  • TypeScript cannot provide type checking
  • IntelliSense becomes limited

Interview Tip

Definitely know:

  • Difference between .ts and .d.ts
  • Why DefinitelyTyped exists

** 7. How do you generate declaration files?

TypeScript can automatically generate .d.ts files.

tsconfig.json

{
"compilerOptions": {
"declaration": true
}
}

Compile Command

tsc

Output

app.ts
app.js
app.d.ts

Use Case

Useful when:

  • Building libraries
  • Publishing npm packages
  • Sharing types with consumers

Interview Insight

Frequently asked in:

  • Library/package development interviews

* 8. What is TypeScript Definition Manager (TSD)?

TSD was an old package manager used to install TypeScript definition files.

Example

tsd install jquery --save

Current Status

TSD is deprecated.

Modern projects use:

npm install @types/jquery

DefinitelyTyped

Most typings now come from:
DefinitelyTyped

Example

npm install @types/lodash

Interview Tip

Mention:

  • TSD is obsolete
  • @types is the modern approach

** 9. What are the steps to include a type definition file?

Step 1: Install typings

npm install @types/lodash

Step 2: Import library

import _ from "lodash";

Step 3: Use library with type support

_.chunk([1,2,3,4], 2);

Manual Inclusion

You can also manually include .d.ts files.

Example

/// <reference path="custom.d.ts" />

Or configure in tsconfig.json.

Interview Insight

Interviewers may ask:

  • How TypeScript finds type definitions
  • Role of node_modules/@types

*** 10. What are Ambient Declarations in TypeScript?

Ambient declarations tell TypeScript about variables, functions, or modules that exist elsewhere.

They use the declare keyword.

Example

declare var message: string;

Function Example

declare function greet(name: string): void;

Module Example

declare module "my-library";

Use Cases

  • JavaScript libraries
  • Global variables
  • Browser APIs
  • Legacy codebases

Important Point

Ambient declarations:

  • Describe structure
  • Do NOT provide implementation

Interview Tip

Very common follow-up:

  • Difference between declare and actual implementation

Example:

declare function test(): void;

This only tells TypeScript:

“This function exists somewhere.”

It does not create the function.

** 11. When should you use the declare keyword?

The declare keyword is used when a variable, function, class, or module already exists externally, and you only want to inform TypeScript about its type.

It is commonly used for:

  • External JavaScript libraries
  • Global variables
  • Browser APIs
  • Third-party scripts

Example: Global Variable

declare var username: string;

console.log(username);

Example: Function Declaration

declare function greet(name: string): void;

Important Point

declare:

  • Provides type information only
  • Does NOT create implementation

Interview Insight

Common follow-up:

What is the difference between declare and actual implementation?

declare function test(): void;

This only tells TypeScript:

“This function exists somewhere.”


*** 12. How do you use external JavaScript libraries in TypeScript?

External JavaScript libraries can be used in TypeScript by adding type definitions.


Step 1: Install Library

Example:

npm install lodash

Step 2: Install Type Definitions

npm install @types/lodash

Step 3: Import and Use

import _ from "lodash";

const result = _.chunk([1,2,3,4], 2);

console.log(result);

What if Type Definitions Do Not Exist?

You can:

  • Create custom .d.ts files
  • Use ambient declarations

Example:

declare module "my-library";

Interview Insight

Frequently asked:

  • Role of @types
  • How TypeScript supports JavaScript libraries
  • What happens if typings are missing

** 13. What are typings in TypeScript?

Typings are type definition files that describe the structure and types of JavaScript code.

They help TypeScript understand:

  • Variables
  • Functions
  • Classes
  • Modules

Example

declare function add(a: number, b: number): number;

Why Typings Are Important

  • Enable IntelliSense
  • Improve type checking
  • Reduce runtime errors
  • Improve developer productivity

Sources of Typings

  1. Built-in typings
  2. @types packages
  3. Custom .d.ts files

Example

npm install @types/react

Interview Tip

Typings are usually stored inside:

node_modules/@types

*** 14. What is the difference between interface and type?

Both interface and type define custom types, but they have some differences.


Interface Example

interface User {
name: string;
age: number;
}

Type Example

type User = {
name: string;
age: number;
};

Key Differences

FeatureInterfaceType
Object ShapeYesYes
Union TypesNoYes
Primitive AliasNoYes
Extendingextends& intersection
Declaration MergingSupportedNot Supported

Union Example (Only with type)

type Status = "success" | "error";

Interface Merging Example

interface Person {
name: string;
}

interface Person {
age: number;
}

Merged result:

{
name: string;
age: number;
}

Interview Recommendation

Use interface when:

  • Defining object structures
  • Designing APIs
  • Working with OOP

Use type when:

  • Using unions
  • Tuples
  • Complex type compositions

*** 15. When should you use interfaces vs classes?

Interfaces define structure/contracts, while classes provide implementation.


Use Interface When:

  • Only structure is needed
  • No implementation required
  • Building reusable contracts

Example

interface Employee {
name: string;
work(): void;
}

Use Class When:

  • Implementation is needed
  • Object creation is required
  • OOP features are required

Example

class Developer {
name: string;

constructor(name: string) {
this.name = name;
}

work() {
console.log("Coding");
}
}

Interview Insight

Common question:

Can a class implement an interface?

Answer:
Yes.

interface Animal {
sound(): void;
}

class Dog implements Animal {
sound() {
console.log("Bark");
}
}

*** 16. What is the difference between classes and interfaces?

FeatureClassInterface
Contains ImplementationYesNo
Object CreationYesNo
ConstructorYesNo
Access ModifiersYesNo
InheritanceYesYes
Runtime PresenceYesNo
Used ForBehavior + DataContract/Structure

Interface Example

interface Car {
start(): void;
}

Class Example

class BMW implements Car {
start() {
console.log("Car Started");
}
}

Important Point

Interfaces disappear after TypeScript compilation.

Classes become JavaScript code.


** 17. What is the default access modifier in TypeScript?

The default access modifier in TypeScript is:

public

Example

class User {
name: string; // public by default
}

Equivalent to:

class User {
public name: string;
}

Access Modifiers in TypeScript

ModifierAccessible Inside ClassChild ClassOutside Class
publicYesYesYes
protectedYesYesNo
privateYesNoNo

Interview Tip

Very common interview question:

Difference between private and protected


*** 18. Can base class constructors be called from child classes?

Yes.

The child class can call the base class constructor using:

super()

Example

class Person {
constructor(public name: string) {
console.log("Parent Constructor");
}
}

class Employee extends Person {
constructor(name: string) {
super(name);
console.log("Child Constructor");
}
}

const emp = new Employee("John");

Output

Parent Constructor
Child Constructor

Important Rule

In derived classes:

super()

must be called before using:

this

Interview Insight

Common follow-up:

Why is super() mandatory?

Because parent class initialization must happen first.


** 19. How do you overload constructors in TypeScript?

TypeScript does not support multiple constructor implementations directly.

Instead, constructor overloading is achieved using:

  • Multiple constructor signatures
  • Single implementation

Example

class User {
name: string;

constructor();
constructor(name: string);

constructor(name?: string) {
this.name = name || "Guest";
}
}

const u1 = new User();
const u2 = new User("Jitendra");

Important Point

TypeScript allows:

  • Multiple constructor declarations
  • Only one implementation

Interview Tip

Commonly confused with Java/C++ constructor overloading.


*** 20. Are strongly typed function parameters possible in TypeScript?

Yes.

TypeScript supports strongly typed parameters.


Example

function add(a: number, b: number): number {
return a + b;
}

Invalid Call

add("10", 20);

TypeScript Error:

Argument of type 'string' is not assignable to parameter of type 'number'

Benefits

  • Compile-time checking
  • Better IntelliSense
  • Fewer runtime errors
  • Better maintainability

Optional Parameters

function greet(name?: string) {
console.log(name);
}

Default Parameters

function greet(name: string = "Guest") {
console.log(name);
}

Rest Parameters

function sum(...nums: number[]) {
return nums.reduce((a, b) => a + b);
}

* 21. How can classes inside modules be accessible outside?

Classes can be accessed outside a module using:

  • export
  • import

Export Class

export class User {
constructor(public name: string) {}
}

Import Class

import { User } from "./User";

const user = new User("Jitendra");

Default Export Example

export default class Employee {
}

Import:

import Employee from "./Employee";

Interview Insight

Common follow-up:

  • Difference between named export and default export
  • Difference between module and namespace 

** 21. What are relative and non-relative imports?

TypeScript supports two types of imports:

  1. Relative Imports
  2. Non-Relative Imports

1. Relative Imports

Relative imports use:

./
../

They specify the exact file location relative to the current file.


Example

import { User } from "./models/User";

Explanation

  • ./ → current directory
  • ../ → parent directory

2. Non-Relative Imports

Non-relative imports import modules from:

  • node_modules
  • Path aliases
  • External libraries

Example

import express from "express";

Or:

import { User } from "app/models/User";

Key Difference

Relative ImportNon-Relative Import
Uses file pathUses module/package name
Starts with ./ or ../Does not start with ./
Used for local filesUsed for packages/modules

Interview Insight

Common follow-up:

Which import type is better for large projects?

Large projects often prefer:

  • Non-relative imports
  • Path aliases

Because they improve readability.


** 23. What are Map files and why are they useful?

Map files (Source Maps) connect compiled JavaScript code back to original TypeScript code.

They usually have:

.js.map

extension.


Why They Are Useful

Source maps help developers:

  • Debug TypeScript directly
  • View original .ts files in browser DevTools
  • Trace errors easily

Example

Files generated:

app.ts
app.js
app.js.map

Enable Source Maps

tsconfig.json

{
"compilerOptions": {
"sourceMap": true
}
}

Workflow

TypeScript:

let message: string = "Hello";

Compiled JavaScript:

var message = "Hello";

Source map links both files.


Interview Tip

Source maps are extremely important in:

  • Frontend debugging
  • Production debugging
  • Webpack/Vite projects

*** 24. Can TypeScript be used for backend development?

Yes.

TypeScript is widely used for backend development.

It runs on:
Node.js


Popular Backend Frameworks

  • NestJS
  • Express.js
  • Fastify

Advantages of Using TypeScript in Backend

BenefitExplanation
Type SafetyFewer runtime errors
Better IDE SupportIntelliSense/autocomplete
ScalabilityEasier large project management
MaintainabilityCleaner architecture
Modern FeaturesAsync/await, decorators, modules

Example

import express from "express";

const app = express();

app.get("/", (req, res) => {
res.send("Hello TypeScript");
});

app.listen(3000);

Common Backend Use Cases

  • REST APIs
  • GraphQL APIs
  • Microservices
  • Authentication systems
  • Enterprise applications

Interview Insight

Very common interview question:

Why use TypeScript instead of JavaScript for backend?

Main answer:

  • Better scalability
  • Safer code
  • Easier maintenance

*** 25. How do modules help organize TypeScript code?

Modules help split code into smaller, reusable, maintainable files.

They improve:

  • Code organization
  • Reusability
  • Encapsulation
  • Scalability

Example Structure

src/
├── models/
├── services/
├── controllers/
└── utils/

Export Module

export class User {
}

Import Module

import { User } from "./User";

Benefits of Modules

BenefitExplanation
ReusabilityReuse code across files
EncapsulationAvoid global scope pollution
MaintainabilityEasier debugging
ScalabilityBetter large application structure

Interview Tip

Modules are heavily used in:

  • Angular
  • React
  • Node.js
  • Enterprise architectures

*** 26. Explain optional static typing in TypeScript.

TypeScript uses optional static typing.

This means:

  • You can define types if needed
  • Type inference can also automatically detect types

Explicit Typing

let age: number = 25;

Type Inference

let age = 25;

TypeScript automatically infers:

number

Benefits

BenefitExplanation
FlexibilityDevelopers can choose typing level
SafetyDetects errors early
Better ProductivityLess manual typing needed

Example Error

let age: number = "25";

Error:

Type 'string' is not assignable to type 'number'

Interview Insight

Common follow-up:

Is TypeScript fully statically typed?

Answer:
No.
It supports optional static typing.


** 27. What is conditional typing in TypeScript?

Conditional types allow types to be selected based on conditions.

Syntax:

T extends U ? X : Y

Example

type IsString<T> = T extends string ? true : false;

Usage

type A = IsString<string>; // true
type B = IsString<number>; // false

Real-World Example

type ApiResponse<T> = T extends string
? string
: number;

Why Useful?

Conditional types help:

  • Build advanced reusable types
  • Create utility types
  • Improve type flexibility

Common Built-in Utility Types

  • Exclude
  • Extract
  • ReturnType
  • NonNullable

Interview Insight

Conditional types are common in:

  • Advanced TypeScript interviews
  • Framework internals
  • Utility libraries

*** 28. Explain function overloading implementation in TypeScript.

Function overloading allows multiple function signatures with different parameter types.

TypeScript supports:

  • Multiple declarations
  • One implementation

Example

function add(a: number, b: number): number;
function add(a: string, b: string): string;

function add(a: any, b: any): any {
return a + b;
}

Usage

add(10, 20);
add("Hello ", "World");

Important Rules

RuleDescription
Multiple SignaturesAllowed
Single ImplementationMandatory
Implementation SignatureUsually generic/any

Why Use Function Overloading?

  • Better readability
  • Better IntelliSense
  • Stronger type safety

Interview Tip

Common follow-up:

Difference between union types and function overloading?

Union Types

function test(value: string | number)

Overloading

Allows different return types and behaviors.


*** 29. What is the use of export and import keywords?

export and import are used to share code between modules/files.

They support modular programming.


Export Example

export class User {
}

Import Example

import { User } from "./User";

Default Export

export default class Employee {
}

Import:

import Employee from "./Employee";

Why Important?

BenefitExplanation
ReusabilityUse code in multiple files
MaintainabilityBetter organization
EncapsulationAvoid global variables
ScalabilityEasier project growth

Types of Exports

TypeSyntax
Named Exportexport {}
Default Exportexport default

Interview Insight

Commonly asked:

  • Difference between named and default exports
  • Benefits of modular programming

*** 30. How do you create reusable components using generics?

Generics help create reusable, type-safe components that work with multiple data types.


Generic Function Example

function identity<T>(value: T): T {
return value;
}

Generic Interface Example

interface ApiResponse<T> {
data: T;
success: boolean;
}

Generic Class Example

class Storage<T> {
private items: T[] = [];

add(item: T) {
this.items.push(item);
}

getItems(): T[] {
return this.items;
}
}

Usage

const numberStorage = new Storage<number>();

numberStorage.add(10);

React Generic Component Example

type Props<T> = {
items: T[];
};

function List<T>({ items }: Props<T>) {
return <div>{items.length}</div>;
}

Benefits of Generics

BenefitExplanation
ReusabilitySame component for multiple types
Type SafetyPrevent invalid data
MaintainabilityCleaner architecture
ScalabilityBetter enterprise code

Interview Insight

Very frequently asked:

Why use generics instead of any?

Answer:
Generics maintain type safety while keeping code reusable.

** 31. What are property decorators and how are they used?

Property decorators are special functions used to observe, modify, or add metadata to class properties.

They are commonly used in:

  • Angular
  • NestJS
  • Validation libraries
  • Dependency Injection systems

Syntax

Property decorators use the @ symbol.


Example

function LogProperty(target: any, propertyKey: string) {
console.log(`Property Name: ${propertyKey}`);
}

class User {
@LogProperty
name: string;
}

Parameters

ParameterDescription
targetClass prototype
propertyKeyProperty name

Real-World Example

class Product {
@Required
title: string;
}

Enable Decorators

tsconfig.json

{
"compilerOptions": {
"experimentalDecorators": true
}
}

Interview Insight

Very common in:

  • Angular interviews
  • NestJS interviews

Common follow-up:

Difference between class decorators and property decorators


*** 32. How does TypeScript support compile-time error checking?

TypeScript checks code for errors during compilation before running the application.

This is called:

Compile-time error checking

Example

let age: number = "25";

TypeScript Error:

Type 'string' is not assignable to type 'number'

What TypeScript Checks

Check TypeExample
Type ErrorsAssigning string to number
Missing PropertiesObject structure mismatch
Invalid Function ArgumentsWrong parameter types
Null IssuesUndefined/null access
Access Modifier ViolationsAccessing private members

Example

function add(a: number, b: number) {
return a + b;
}

add("10", 20);

Benefits

BenefitExplanation
Early Bug DetectionErrors caught before runtime
Better Code QualitySafer applications
Better ToolingIntelliSense support
Easier MaintenanceCleaner large-scale projects

Interview Tip

Common interview question:

Does TypeScript remove all runtime errors?

Answer:
No.
It only reduces many common errors during development.


*** 33. What is strict null checking?

Strict null checking prevents null and undefined from being assigned to variables unless explicitly allowed.

It improves application safety.


Enable Strict Null Checking

tsconfig.json

{
"compilerOptions": {
"strictNullChecks": true
}
}

Example Without Strict Null Checking

let name: string = null;

Allowed in loose mode.


Example With Strict Null Checking

let name: string = null;

Error:

Type 'null' is not assignable to type 'string'

Correct Approach

let name: string | null = null;

Benefits

BenefitExplanation
Prevents Null ErrorsSafer applications
Better ReliabilityFewer crashes
Stronger Type SafetyExplicit nullable types

Interview Insight

Very frequently asked:

Difference between undefined and null


*** 34. How does TypeScript support ES6+ features?

TypeScript supports modern JavaScript (ES6+) features and can transpile them into older JavaScript versions.


Supported ES6+ Features

FeatureExample
Arrow Functions()=>{}
Classesclass User {}
Modulesimport/export
Template Literals`Hello`
Async/Awaitasync function()
Destructuring{name}
Spread Operator...arr

Example

const add = (a: number, b: number) => a + b;

Async/Await Example

async function fetchData() {
return "Data";
}

Transpilation Support

TypeScript converts modern code into compatible JavaScript versions.

tsconfig.json

{
"compilerOptions": {
"target": "ES5"
}
}

Interview Insight

Common follow-up:

Why use TypeScript if JavaScript already supports ES6?

Answer:
TypeScript adds:

  • Type safety
  • Better tooling
  • Compile-time checking

*** 35. How do you implement encapsulation in TypeScript?

Encapsulation means hiding internal data and controlling access through methods.

TypeScript implements encapsulation using:

  • private
  • protected
  • public

Example

class BankAccount {
private balance: number = 1000;

getBalance(): number {
return this.balance;
}
}

const acc = new BankAccount();

console.log(acc.getBalance());

Invalid Access

console.log(acc.balance);

Error:

Property 'balance' is private

Benefits

BenefitExplanation
Data ProtectionPrevent direct modification
Better SecurityControlled access
Better MaintainabilityCleaner architecture

Interview Tip

Common question:

Difference between private and protected


*** 36. How do you implement polymorphism in TypeScript?

Polymorphism allows one method to behave differently in different classes.

Usually implemented using:

  • Method overriding
  • Interfaces
  • Inheritance

Example Using Method Overriding

class Animal {
sound() {
console.log("Animal Sound");
}
}

class Dog extends Animal {
sound() {
console.log("Bark");
}
}

class Cat extends Animal {
sound() {
console.log("Meow");
}
}

Usage

const animals: Animal[] = [
new Dog(),
new Cat()
];

animals.forEach(a => a.sound());

Output

Bark
Meow

Benefits

BenefitExplanation
FlexibilitySame interface, different behavior
ReusabilityCleaner code
ExtensibilityEasier scaling

Interview Insight

Very common OOP interview question.


*** 37. How do you implement abstraction in TypeScript?

Abstraction hides implementation details and exposes only essential functionality.

Implemented using:

  • Abstract classes
  • Interfaces

Abstract Class Example

abstract class Vehicle {
abstract start(): void;

stop() {
console.log("Vehicle Stopped");
}
}

class Car extends Vehicle {
start() {
console.log("Car Started");
}
}

Important Rules

RuleDescription
Abstract Class Object CreationNot allowed
Abstract MethodsMust be implemented
Can Have Normal MethodsYes

Invalid Example

const v = new Vehicle();

Error because abstract classes cannot be instantiated.


Interview Insight

Common follow-up:

Difference between abstraction and encapsulation


*** 38. How do you implement inheritance in TypeScript?

Inheritance allows one class to acquire properties and methods of another class.

Implemented using:

extends

Example

class Person {
name: string = "Jitendra";

walk() {
console.log("Walking");
}
}

class Employee extends Person {
work() {
console.log("Working");
}
}

Usage

const emp = new Employee();

emp.walk();
emp.work();

Benefits

BenefitExplanation
Code ReuseReuse parent functionality
Better StructureCleaner hierarchy
ExtensibilityEasy feature extension

Types of Inheritance Supported

  • Single Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance

Interview Tip

TypeScript does NOT support:

Multiple Inheritance

Directly.

Mixins can be used instead.


** 39. How do you create reusable modules?

Reusable modules are created using:

  • export
  • import

Each module contains related functionality.


Utility Module Example

math.ts

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

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

Import Module

app.ts

import { add, subtract } from "./math";

console.log(add(10, 20));

Best Practices

PracticeExplanation
Keep Modules SmallEasier maintenance
Group Related LogicBetter readability
Use Named ExportsBetter clarity
Avoid Global VariablesBetter encapsulation

Interview Insight

Reusable modules are important in:

  • Enterprise applications
  • Large frontend projects
  • Backend services

*** 40. How does transpilation work in TypeScript?

Transpilation is the process of converting TypeScript code into JavaScript.

The TypeScript compiler:

tsc

performs this conversion.


Workflow

TypeScript (.ts)

TypeScript Compiler (tsc)

JavaScript (.js)

Example

TypeScript Code

let age: number = 25;

Transpiled JavaScript

var age = 25;

Compilation Command

tsc app.ts

tsconfig.json Example

{
"compilerOptions": {
"target": "ES5",
"module": "commonjs"
}
}

What Happens During Transpilation?

StepDescription
Type CheckingDetect errors
Remove TypesTypes removed from output
Convert SyntaxES6+ → ES5 if needed
Generate JSBrowser/Node compatible code

Important Point

TypeScript types do NOT exist at runtime.

After compilation:

  • Only JavaScript remains

Interview Insight

Very common interview question:

Difference between compilation and transpilation

Compilation

Converts one language to another lower-level language.

Transpilation

Converts one high-level language to another high-level language.