ExamAdda LogoExamAdda
PremiumDSA Animations
JAVASCRIPTMYSQLPYTHONINTERVIEWDBMSROADMAPSMACHINE LEARNING

JAVASCRIPT

  • JavaScript for Freshers
  • JavaScript for Intermediate
  • JavaScript Advanced
  • JavaScript Scenario Based Questions

Microservices

  • Microservices for Freshers
  • Microservices for Intermediate
  • Microservices Advanced

DBMS

  • DBMS for Freshers
  • DBMS for Intermediate
  • DBMS Advanced
  • DBMS Scenario-Based Questions

MongoDB

  • MongoDB for Freshers
  • MongoDB for Intermediate
  • MongoDB Advanced

TypeScript

  • TypeScript for Freshers
  • TypeScript for Intermediate
  • TypeScript Advanced
  • Frequently Asked Coding

ReactJs

  • ReactJs for Freshers
  • ReactJs for Intermediate
  • ReactJs Advanced

Python

  • Python for Freshers
  • Python for Intermediate
  • Python Advanced
  • Python Scenario-Based Questions

NODEJS

  • Nodejs for Freshers
  • NodeJS for Intermediate
  • Nodejs Advanced

DSA Interview

  • DSA for Freshers
  • DSA for Intermediate
  • DSA Advanced

Computer Network

  • Network for Freshers
  • Network for Intermediate
  • Network Advanced
  • Network Scenario Based Questions

Operating System

  • OS for Freshers
  • OS for Intermediate
  • OS Advanced

HTML

  • HTML for Freshers
  • HTML for Intermediate
  • HTML Advanced

CSS

  • CSS for Freshers
  • CSS for Intermediate
  • CSS Advanced

NEXTJS

  • NextJs for Freshers
  • NextJs for Intermediate
  • NextJs Advanced

C

  • C for Freshers
  • C for Intermediate
  • C Advanced

Golang

  • Golang for Freshers
  • Golang for Intermediate
  • Golang Advanced

Rust

  • Rust for Freshers
  • Rust for Intermediate
  • Rust Advanced
  • Rust Coding

HR

  • HR for Freshers
  • HR for Intermediate
  • HR Advanced

JAVA

  • Java for Freshers
  • Java for Intermediate
  • Java Advanced

Top 70 TypeScript Interview Questions and Answers for Freshers (2026)

Last updated: May 7, 2026
Author :Jitendra KumarJitendra Kumar

***1. What is TypeScript?

TypeScript is an open-source programming language developed by Microsoft that is built on top of JavaScript.

It is a superset of JavaScript, which means:

  • All JavaScript code is valid TypeScript code.
  • TypeScript adds extra features like:
    • Static typing
    • Interfaces
    • Classes
    • Generics
    • Advanced tooling support

TypeScript code is converted (compiled/transpiled) into JavaScript before running in the browser or Node.js environment.

Example

function greet(name: string): string {
return "Hello " + name;
}

console.log(greet("Jitendra"));

Compiled JavaScript

function greet(name) {
return "Hello " + name;
}

console.log(greet("Jitendra"));

Key Points for Interview

  • TypeScript = JavaScript + Type Safety
  • It helps detect errors during development.
  • It improves code readability and maintainability.
  • Widely used in Angular, React, Node.js, and enterprise applications.

***2. Why do we need TypeScript?

JavaScript is dynamically typed, which can cause runtime errors that are difficult to debug in large applications.

TypeScript is needed to:

  • Improve code quality
  • Detect errors early during development
  • Make large-scale applications easier to maintain
  • Improve developer productivity with better IDE support

Problems in JavaScript

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

add(10, "20"); // Unexpected result: "1020"

Because JavaScript does not enforce data types, bugs may occur at runtime.

TypeScript Solution

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

add(10, 20); // Correct

If we pass a string, TypeScript shows an error during development.

Why Companies Prefer TypeScript

  • Better maintainability
  • Safer refactoring
  • Easier teamwork in large projects
  • Improved scalability
  • Better IntelliSense and auto-completion

Key Interview Points

  • Prevents runtime errors
  • Supports large applications
  • Provides static typing
  • Improves development speed

***3. Why should we use TypeScript instead of JavaScript?

TypeScript provides several advanced features that JavaScript does not provide directly.

Developers use TypeScript because it makes applications:

  • More reliable
  • Easier to scale
  • Easier to maintain

Major Reasons to Use TypeScript

FeatureJavaScriptTypeScript
Static Typing❌✅
Compile-Time Error Checking❌✅
Interfaces❌✅
Generics❌✅
Better IDE SupportLimitedExcellent
Easier Refactoring❌✅

Example

JavaScript

 let age: number = 25; age = "twenty five"; //Allowed

TypeScript

let age: number = 25;age = "twenty five";// Allowed

Benefits Over JavaScript

  • Early bug detection
  • Cleaner code structure
  • Better code documentation
  • Easier debugging
  • Better collaboration in teams

Interview Tip

Interviewers often ask:

“If JavaScript already exists, why TypeScript?”

Best answer:

“TypeScript improves JavaScript development by adding static typing, better tooling, and scalability support for large applications.”

***4. What are the differences between TypeScript and JavaScript?

FeatureJavaScriptTypeScript
Developed ByNetscapeMicrosoft
TypingDynamicStatic
CompilationNo compilation requiredCompiles to JavaScript
Error DetectionRuntimeCompile Time
OOP SupportPartialStrong
Interfaces❌✅
Generics❌✅
Tooling SupportModerateExcellent
Learning CurveEasySlightly Higher
File Extension.js.ts

Example

JavaScript

let value = 10;
value = "Hello"; // Allowed

TypeScript

let value: number = 10;
value = "Hello"; // Error

Key Interview Point

TypeScript improves JavaScript by adding type safety and advanced development features.

**5. What are the advantages/benefits of using TypeScript?

1. Static Typing

Helps catch errors during development.

let price: number = 100;

2. Better IDE Support

Provides:

  • Auto-completion
  • IntelliSense
  • Navigation
  • Refactoring support

3. Early Error Detection

Errors are found at compile time instead of runtime.

4. Better Code Maintainability

Makes large projects easier to manage.

5. Supports Modern JavaScript Features

Supports ES6+ features and compiles to older JavaScript versions.

6. Improved Readability

Type definitions make code self-documenting.

7. Strong Object-Oriented Features

Supports:

  • Classes
  • Interfaces
  • Access modifiers
  • Inheritance

Key Interview Point

TypeScript improves productivity, maintainability, and application reliability.

*6. What are the disadvantages of using TypeScript?

Although TypeScript has many advantages, it also has some limitations.

Disadvantages

1. Compilation Required

TypeScript must be compiled into JavaScript before execution.

2. Learning Curve

Developers need to learn:

  • Types
  • Interfaces
  • Generics
  • Advanced concepts

3. Increased Development Time Initially

Writing type definitions may take extra time in the beginning.

4. More Configuration

Requires setup files like:

tsconfig.json

5. Not Executed Directly by Browsers

Browsers understand JavaScript, not TypeScript.

Interview Tip

Always mention:

“The advantages of TypeScript generally outweigh its disadvantages, especially for large-scale applications.”

**7. What are the features of TypeScript?

Major Features of TypeScript

1. Static Typing

let username: string = "Jitendra";

2. Object-Oriented Programming Support

Supports:

  • Classes
  • Interfaces
  • Inheritance
  • Encapsulation

3. Interfaces

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

4. Generics

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

5. Type Inference

Automatically detects data types.

let city = "Patna";

6. Access Modifiers

Supports:

  • public
  • private
  • protected

7. Compatibility with JavaScript

Existing JavaScript projects can gradually migrate to TypeScript.

8. Modern ES Features

Supports:

  • Arrow functions
  • Async/await
  • Modules
  • Destructuring

Key Interview Point

TypeScript combines JavaScript flexibility with strong typing and modern development features.

*8. What are the components of TypeScript?

TypeScript mainly consists of the following components:

ComponentDescription
TypeScript LanguageIncludes syntax, types, and features
TypeScript Compiler (TSC)Converts TypeScript into JavaScript
TypeScript Language ServicesProvides IDE support like IntelliSense and error checking

1. TypeScript Language

Provides:

  • Types
  • Interfaces
  • Classes
  • Modules

2. TypeScript Compiler (TSC)

Command:

tsc app.ts

Converts:

app.ts

into:

app.js

3. TypeScript Language Services

Improves developer experience with:

  • Auto-completion
  • Error detection
  • Refactoring tools

Interview One-Liner

“The core components of TypeScript are the TypeScript language, compiler, and language services.”

*9. Who developed TypeScript and what is the latest stable version?

TypeScript was developed by Microsoft.

The main creator of TypeScript is Anders Hejlsberg, who is also known for creating C#.

Important Facts

  • First released in: 2012
  • Developed and maintained by: Microsoft
  • File Extension: .ts

Latest Stable Version

The latest stable version changes frequently.

You can check the official latest version here:

TypeScript Official Website

Interview Tip

Instead of guessing the exact version number in interviews, say:

“TypeScript is actively maintained by Microsoft, and the latest stable version can be checked on the official TypeScript website.”

**10. How do you install TypeScript?

TypeScript is installed using Node Package Manager (NPM).

Step 1: Install Node.js

Download and install Node.js from:

Node.js Official Website


Step 2: Install TypeScript Globally

npm install -g typescript

Step 3: Verify Installation

tsc --version

This command displays the installed TypeScript version.


Step 4: Create TypeScript File

// app.ts
let message: string = "Hello TypeScript";
console.log(message);

Step 5: Compile TypeScript File

tsc app.ts

This generates:

app.js

Step 6: Run JavaScript File

node app.js

Interview Tip

Interviewers may ask:

“What command is used to install TypeScript globally?”

Answer:

npm install -g typescript
11. How do you compile a TypeScript file?

TypeScript files are compiled into JavaScript using the TypeScript Compiler (TSC).

The compiler converts .ts files into .js files because browsers understand JavaScript, not TypeScript.

Step-by-Step Compilation

Step 1: Create a TypeScript File

let message: string = "Hello TypeScript";
console.log(message);

Save it as:

app.ts

Step 2: Compile the File

Use the following command:

tsc app.ts

Step 3: Generated JavaScript File

After compilation:

app.js

is generated automatically.

Step 4: Run the JavaScript File

node app.js

Important Interview Points

  • tsc stands for TypeScript Compiler.
  • TypeScript code cannot run directly in browsers.
  • Compilation converts TypeScript into plain JavaScript.

One-Line Interview Answer

“We compile a TypeScript file using the tsc filename.ts command.”

12. Can TypeScript files compile automatically on changes?

Yes. TypeScript supports automatic compilation using Watch Mode.

Watch mode continuously monitors TypeScript files and recompiles them whenever changes are detected.

Command for Auto Compilation

tsc app.ts --watch

OR

tsc --watch

Short form:

tsc -w

How It Works

  • TypeScript watches the file.
  • When you save changes:
    • It recompiles automatically.
    • Updated JavaScript is generated instantly.

Benefits

  • Faster development
  • Saves manual compilation time
  • Useful in large projects

Example Workflow

app.ts  -->  Automatically Compiled  -->  app.js

Important Interview Point

Watch mode is commonly used during development to improve productivity.

*13. What is tsconfig.json?

tsconfig.json is the configuration file used by TypeScript projects.

It defines:

  • Compiler options
  • Project settings
  • Files to include/exclude
  • Target JavaScript version

Why It Is Important

Instead of passing compiler settings manually every time, we define them once inside tsconfig.json.

Example

{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"strict": true,
"outDir": "./dist"
}
}

Common Compiler Options

OptionPurpose
targetJavaScript version output
moduleModule system
strictEnables strict type checking
outDirOutput folder
rootDirSource folder
sourceMapGenerates source maps

Create tsconfig.json

tsc --init

Key Interview Points

  • Central configuration file for TypeScript projects
  • Improves maintainability
  • Required in most enterprise applications

One-Line Interview Answer

“tsconfig.json is the configuration file that controls TypeScript compiler behavior and project settings.”

14. What are source map (.map) files in TypeScript?*

Source map files (.map) help developers debug TypeScript code in the browser.

They map the generated JavaScript code back to the original TypeScript code.

Why Source Maps Are Needed

Browsers execute JavaScript, not TypeScript.

Without source maps:

  • Debugging becomes difficult
  • Error locations may not match original TypeScript code

Example

app.ts

Compiles into:

app.js
app.js.map

Enable Source Maps

Inside tsconfig.json:

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

Benefits

  • Easier debugging
  • Better developer experience
  • Shows original TypeScript in browser developer tools

Important Interview Point

Source maps connect JavaScript code with original TypeScript source code for debugging purposes.

*15. What are the built-in data types in TypeScript?

TypeScript provides several built-in data types to define the type of variables.

Main Built-in Data Types

Data TypeDescription
numberNumeric values
stringText values
booleantrue/false
nullEmpty value
undefinedUndefined variable
anyAny type of value
voidNo return value
neverValue never occurs
objectNon-primitive values
arrayCollection of values
tupleFixed-size array
enumNamed constants
unknownSafer alternative to any

Examples

let age: number = 25;
let name: string = "Jitendra";
let isActive: boolean = true;

Key Interview Point

TypeScript data types improve type safety and reduce runtime errors.

*16. Explain the data types available in TypeScript.

TypeScript data types are categorized into different groups.

1. Number

Used for numeric values.

let price: number = 100;

2. String

Used for text values.

let username: string = "Jitendra";

3. Boolean

Stores true or false.

let isLoggedIn: boolean = true;

4. Array

Stores multiple values.

let marks: number[] = [90, 80, 70];

5. Tuple

Fixed-size array with defined types.

let user: [string, number] = ["Jitendra", 25];

6. Enum

Represents named constants.

enum Role {
Admin,
User
}

7. Any

Can hold any value.

let value: any = "Hello";

8. Void

Used mainly for functions with no return value.

function print(): void {
console.log("Hello");
}

9. Never

Represents values that never occur.

function throwError(): never {
throw new Error("Error");
}

10. Unknown

Safer alternative to any.

let data: unknown;

Interview Tip

Interviewers commonly ask:

“Difference between any, unknown, void, and never.”

Prepare these properly.

17. What are user-defined data types in TypeScript?*

User-defined data types are custom types created by developers according to application requirements.

Types of User-Defined Data Types

TypeDescription
InterfaceDefines object structure
ClassBlueprint for objects
EnumNamed constants
Type AliasCustom type names

1. Interface

interface Employee {
id: number;
name: string;
}

2. Class

class Person {
name: string = "Jitendra";
}

3. Enum

enum Direction {
Up,
Down
}

4. Type Alias

type ID = number | string;

Important Interview Point

User-defined data types help create reusable and scalable code structures.

*18. What is the any type in TypeScript?

The any type allows a variable to store values of any data type.

It disables type checking for that variable.

Example

let value: any = 10;

value = "Hello";
value = true;

Why It Is Used

Used when:

  • Type is unknown
  • Migrating JavaScript to TypeScript
  • Handling dynamic data

Disadvantages

  • Removes type safety
  • Can introduce runtime errors
  • Reduces TypeScript benefits

Interview Tip

Avoid excessive use of any.

Prefer:

  • specific types
  • unknown
  • interfaces

One-Line Interview Answer

“The any type allows storing any type of value and disables TypeScript type checking.”

19. What is the void type in TypeScript?

The void type represents the absence of a value.

It is mainly used as the return type of functions that do not return anything.

Example

function greet(): void {
console.log("Welcome");
}

Important Points

  • A void function does not return a value.
  • Commonly used in utility functions.

Example with Arrow Function

const printMessage = (): void => {
console.log("Hello");
};

Interview Tip

Difference between:

  • void → function returns nothing
  • never → function never finishes

*20. What is the never type in TypeScript?

The never type represents values that never occur.

It is used when:

  • A function never returns
  • A function always throws an error
  • Infinite loops exist

Example 1: Function Throwing Error

function throwError(message: string): never {
throw new Error(message);
}

Example 2: Infinite Loop

function infiniteLoop(): never {
while (true) {}
}

Difference Between void and never

voidnever
Function completes normallyFunction never completes
Returns nothingNever returns

Important Interview Point

Interviewers frequently ask:

“Difference between void and never.”

Best answer:

  • void → no return value
  • never → function never ends or always throws error

*21. What is null in TypeScript?

In TypeScript, null represents an intentional absence of value.

It means:

“The variable exists, but currently has no value.”

Example

let username: string | null = null;

Here:

  • username can store either:
    • a string
    • or null

Important Points

  • null is a primitive value.
  • Used when value is intentionally empty.
  • Commonly used in APIs and database responses.

Example Use Case

function getUser(): string | null {
return null;
}

Interview Tip

Difference between:

  • null → intentionally empty
  • undefined → value not assigned

One-Line Interview Answer

“null represents an intentional absence of value in TypeScript.”

*22. What is undefined in TypeScript?

undefined means a variable has been declared but has not been assigned a value.

Example

let age: number;

console.log(age); // undefined

Important Points

  • Automatically assigned by JavaScript/TypeScript.
  • Indicates missing initialization.
  • Primitive data type.

Example

function printValue(value?: string) {
console.log(value);
}

If no argument is passed:

  • value becomes undefined

Difference Between null and undefined

nullundefined
Intentionally emptyNot assigned
Assigned manuallyAssigned automatically

Interview Tip

Interviewers frequently ask:

“Difference between null and undefined.”

Keep answer short and clear.

*23. Explain union types in TypeScript.

Union types allow a variable to store multiple types of values.

Union types are created using the | (pipe) operator.

Syntax

let value: string | number;

This means:

  • value can store:
    • string
    • OR number

Example

let id: string | number;

id = 101;
id = "EMP101";

Benefits

  • Flexible type definitions
  • Reduces use of any
  • Improves type safety

Example in Functions

function printId(id: string | number) {
console.log(id);
}

Important Interview Point

Union types are widely used in:

  • APIs
  • React props
  • Dynamic values

Interview Tip

Difference:

  • any → accepts everything without checking
  • Union type → accepts only specified types

One-Line Interview Answer

“Union types allow a variable or parameter to hold more than one specified type.”

*24. Explain type aliases in TypeScript.

A type alias allows developers to create a custom name for a type.

It improves:

  • readability
  • reusability
  • maintainability

Syntax

type TypeName = existingType;

Example

type ID = string | number;

let userId: ID;

userId = 101;
userId = "EMP101";

Example with Object Type

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

Benefits

  • Reusable code
  • Cleaner type definitions
  • Better maintainability

Type Alias vs Interface

Type AliasInterface
Can define unionsMainly object structures
More flexibleBetter for OOP designs

Interview Tip

Interviewers often ask:

“Difference between interface and type alias.”

Mention:

  • Interfaces are mainly for object structures.
  • Type aliases are more flexible.

One-Line Interview Answer

“Type aliases create custom reusable names for existing types.”

*25. Explain type inference in TypeScript.

Type inference means TypeScript automatically detects the type of a variable without explicit type annotation.

Example

let username = "Jitendra";

TypeScript automatically infers:

string

Another Example

let age = 25;

Inferred type:

number

Benefits

  • Reduces extra code
  • Cleaner syntax
  • Improves developer productivity

Explicit vs Inferred

Explicit Typing

let city: string = "Patna";

Inferred Typing

let city = "Patna";

Important Interview Point

Type inference is one of the most useful TypeScript features because it reduces unnecessary type annotations.

One-Line Interview Answer

“Type inference is the ability of TypeScript to automatically determine data types.”

26. What is typeof operator in TypeScript?

The typeof operator is used to determine the type of a variable or value.

Example

let age = 25;

console.log(typeof age);

Output:

number

Common Return Values

Valuetypeof Result
10"number"
"Hello""string"
true"boolean"
undefined"undefined"

Example in Type Guards

function print(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
}
}

Important Interview Point

typeof is heavily used for:

  • Type narrowing
  • Runtime checking
  • Union type handling

One-Line Interview Answer

“The typeof operator returns the data type of a variable or value.”

27. What is the in operator in TypeScript?

The in operator checks whether a property exists inside an object.

It is also used for type narrowing in TypeScript.

Syntax

property in object

Example

type Admin = {
adminAccess: boolean;
};

type User = {
name: string;
};

function check(person: Admin | User) {
if ("adminAccess" in person) {
console.log("Admin");
}
}

Benefits

  • Helps identify object types
  • Used with union types
  • Improves type safety

Important Interview Point

The in operator is commonly used in:

  • Type guards
  • Object validation
  • Dynamic object handling

One-Line Interview Answer

“The in operator checks whether a property exists in an object.”

28. Is TypeScript strictly statically typed?

No. TypeScript is not completely strictly statically typed.

It is called:

Optionally statically typed language

because developers can choose whether to use strict typing or not.

Why?

TypeScript allows:

  • explicit types
  • inferred types
  • dynamic types using any

Example

Strict Typing

let age: number = 25;

Dynamic Typing

let data: any = "Hello";
data = 100;

Important Interview Point

TypeScript provides static typing features but still allows flexibility like JavaScript.

One-Line Interview Answer

“TypeScript is optionally statically typed because it supports both static and dynamic typing.”

29. How is TypeScript optionally statically typed?

Answer

TypeScript is called optionally statically typed because developers can:

  • use strict type checking
  • OR skip type checking using any

This gives flexibility similar to JavaScript.

Example with Static Typing

let salary: number = 50000;

Only numbers are allowed.

Example with Dynamic Typing

let value: any = 100;

value = "Hello";
value = true;

Why It Is Called “Optional”

Because type annotations are not mandatory.

TypeScript can:

  • infer types automatically
  • allow dynamic typing when needed

Important Interview Point

This flexibility makes migration from JavaScript easier.

One-Line Interview Answer

“TypeScript is optionally statically typed because developers can choose between strict typing and dynamic typing.”

30. What are variables in TypeScript?

Variables are named storage locations used to store data values in a program.

In TypeScript, variables can store typed data.

Syntax

let variableName: type = value;

Example

let username: string = "Jitendra";
let age: number = 25;

Ways to Declare Variables

KeywordScopeReassignable
varFunction scopeYes
letBlock scopeYes
constBlock scopeNo

Example

var

var city = "Patna";

let

let age = 25;

const

const PI = 3.14;

Best Practice

Prefer:

  • let for changing values
  • const for fixed values

Avoid excessive use of:

  • var

Important Interview Point

Interviewers frequently ask:

“Difference between var, let, and const.”

Prepare this properly.

31. In how many ways can variables be declared in TypeScript?

Variables in TypeScript can be declared in 3 ways:

KeywordScopeReassignable
varFunction ScopeYes
letBlock ScopeYes
constBlock ScopeNo

1. var

var is the traditional JavaScript variable declaration.

var username = "Jitendra";

Characteristics

  • Function scoped
  • Can be redeclared
  • Can be reassigned

2. let

let was introduced in ES6.

let age = 25;

Characteristics

  • Block scoped
  • Cannot be redeclared in same scope
  • Can be reassigned

3. const

Used for fixed values.

const PI = 3.14;

Characteristics

  • Block scoped
  • Cannot be redeclared
  • Cannot be reassigned

Important Interview Point

Modern TypeScript applications mainly use:

  • let
  • const

Avoid excessive use of:

  • var

One-Line Interview Answer

“Variables in TypeScript can be declared using var, let, and const.”

*32. How do you declare explicitly typed variables?

Explicit typing means manually specifying the data type of a variable during declaration.

Syntax

let variableName: type = value;

Examples

String Variable

let username: string = "Jitendra";

Number Variable

let age: number = 25;

Boolean Variable

let isLoggedIn: boolean = true;

Benefits

  • Improves readability
  • Prevents invalid assignments
  • Provides better type safety

Invalid Example

let salary: number = "50000";

TypeScript will show an error because:

  • string cannot be assigned to number

Important Interview Point

Explicit typing is heavily used in:

  • Enterprise applications
  • APIs
  • Large codebases

One-Line Interview Answer

“Explicitly typed variables are declared by manually specifying their data types using : syntax.”

*33. What are arrays in TypeScript and how do they behave?

Arrays in TypeScript are collections used to store multiple values of the same type.

TypeScript adds type safety to arrays.

Syntax

Method 1

let numbers: number[] = [1, 2, 3];

Method 2

let numbers: Array<number> = [1, 2, 3];

Example

let fruits: string[] = ["Apple", "Banana", "Mango"];

Array Behavior

  • Arrays are dynamic in size.
  • Elements are accessed using indexes.
  • TypeScript ensures only specified types are added.

Invalid Example

let marks: number[] = [90, 80];

marks.push("Hello"); // Error

Common Array Methods

MethodPurpose
push()Add element
pop()Remove last element
map()Transform array
filter()Filter values

Important Interview Point

TypeScript arrays provide:

  • Type safety
  • Better IntelliSense
  • Error prevention

One-Line Interview Answer

“Arrays in TypeScript are typed collections that store multiple values of the same data type.”

34. What are tuples in TypeScript?

Tuples are special arrays with:

  • fixed size
  • fixed order
  • fixed data types

Each element can have a different type.

Syntax

let user: [string, number];

Example

let employee: [string, number] = ["Jitendra", 101];

Here:

  • First value → string
  • Second value → number

Invalid Example

let employee: [string, number] = [101, "Jitendra"];

Type mismatch occurs because order matters.

Tuple vs Array

TupleArray
Fixed structureFlexible structure
Different types allowedUsually same type
Order mattersOrder less strict

Common Use Cases

  • API responses
  • Database records
  • Key-value pairs

Important Interview Point

Interviewers commonly ask:

“Difference between tuple and array.”

One-Line Interview Answer

“A tuple is a fixed-size typed array where each element can have a different type.”

35. How do you create objects in TypeScript?

Objects in TypeScript are created using key-value pairs with defined types.

Syntax

let objectName: {
property: type;
};

Example

let employee: {
id: number;
name: string;
} = {
id: 101,
name: "Jitendra"
};

Using Interface (Recommended)

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

let user: User = {
id: 1,
name: "Rahul"
};

Benefits

  • Better structure
  • Improved readability
  • Type safety

Important Interview Point

In real projects, objects are usually created using:

  • interfaces
  • type aliases
  • classes

One-Line Interview Answer

“Objects in TypeScript are created using typed key-value pairs.”

36. How do you define optional object properties?

Optional properties are properties that may or may not exist in an object.

They are defined using the ? operator.

Syntax

propertyName?: type;

Example

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

Valid Objects

let user1: User = {
name: "Jitendra"
};

let user2: User = {
name: "Rahul",
age: 25
};

Benefits

  • Flexible object creation
  • Useful for APIs/forms
  • Reduces unnecessary properties

Important Interview Point

Optional properties are widely used in:

  • React props
  • API response models
  • Form handling

One-Line Interview Answer

“Optional properties are defined using ? and may or may not exist in an object.”

*37. What are enums in TypeScript?

Enums are used to define a set of named constants.

They improve code readability and maintainability.

Syntax

enum EnumName {
Value1,
Value2
}

Example

enum Direction {
Up,
Down,
Left,
Right
}

Access Enum Values

console.log(Direction.Up);

Output:

0

String Enum Example

enum Status {
Success = "SUCCESS",
Failed = "FAILED"
}

Benefits

  • Better readability
  • Avoids hardcoded values
  • Easier maintenance

Important Interview Point

Enums are commonly used for:

  • status codes
  • user roles
  • application states

One-Line Interview Answer

“Enums are named constants used to represent a group of related values.”

38. Explain template literals in TypeScript.

Template literals are strings enclosed using backticks ` `.

They allow:

  • string interpolation
  • multi-line strings
  • embedded expressions

Syntax

`Hello ${value}`

Example

let name = "Jitendra";

let message = `Hello ${name}`;

Multi-Line Example

let text = `
Welcome
to
TypeScript
`;

Benefits

  • Cleaner string formatting
  • Easier variable embedding
  • Better readability

Important Interview Point

Template literals are heavily used in:

  • React
  • Dynamic HTML generation
  • API messages

One-Line Interview Answer

“Template literals allow embedded expressions and multi-line strings using backticks.”

*39. How do you declare functions with typed annotations?

In TypeScript, function parameters and return types can be explicitly typed.

This improves:

  • readability
  • type safety
  • error checking

Syntax

function functionName(parameter: type): returnType {
}

Example

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

Void Return Example

function printMessage(message: string): void {
console.log(message);
}

Optional Parameter Example

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

Benefits

  • Prevents invalid arguments
  • Better IntelliSense
  • Easier debugging

Important Interview Point

Typed annotations are very important in:

  • APIs
  • enterprise applications
  • reusable functions

One-Line Interview Answer

“Functions with typed annotations define parameter types and return types explicitly.”

*40. What are arrow/lambda functions in TypeScript?

Arrow functions are shorter syntax versions of regular functions introduced in ES6.

They are also called:

  • lambda functions
  • fat arrow functions

Syntax

const functionName = (parameters) => {
};

Example

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

Shorter Version

const square = (num: number): number => num * num;

Benefits

  • Shorter syntax
  • Cleaner code
  • Automatically binds this

Regular Function vs Arrow Function

Regular FunctionArrow Function
Uses function keywordUses =>
Has its own thisInherits parent this
Longer syntaxShorter syntax

Important Interview Point

Interviewers frequently ask:

“Difference between regular functions and arrow functions.”

Focus especially on:

  • syntax
  • this keyword behavior

One-Line Interview Answer

“Arrow functions are concise functions that use => syntax and inherit this from the parent scope.”

41. How do you define optional parameters in functions?

Optional parameters are function parameters that are not mandatory while calling the function.

They are defined using the ? symbol.

Syntax

function functionName(parameter?: type) {
}

Example

function greet(name?: string): void {
console.log(`Hello ${name}`);
}

Function Calls

greet("Jitendra");
greet();

Both are valid.

Important Rules

  • Optional parameters should come after required parameters.
  • They may contain undefined if no value is passed.

Invalid Example

function test(a?: number, b: number) {}

This causes an error because optional parameters cannot appear before required parameters.

Important Interview Point

Optional parameters are commonly used in:

  • APIs
  • utility functions
  • reusable components

One-Line Interview Answer

“Optional parameters are parameters that may or may not receive values and are defined using ?.”

42. What are default parameters in TypeScript?

Default parameters allow assigning default values to function parameters.

If no argument is passed, the default value is used.

Syntax

function functionName(parameter: type = value) {
}

Example

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

Function Calls

greet("Jitendra"); // Hello Jitendra
greet(); // Hello Guest

Benefits

  • Reduces undefined values
  • Simplifies function calls
  • Improves readability

Important Interview Point

Difference between:

  • Optional parameter → may be undefined
  • Default parameter → always has a value

One-Line Interview Answer

“Default parameters assign predefined values to parameters when no argument is passed.”

43. What are rest parameters in TypeScript?

Rest parameters allow a function to accept multiple arguments as an array.

They are represented using ... (spread operator syntax).

Syntax

function functionName(...parameter: type[]) {
}

Example

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

Function Call

sum(10, 20, 30);

Benefits

  • Handles variable number of arguments
  • Cleaner code
  • Flexible functions

Important Interview Point

Rest parameters store all extra arguments inside an array.

One-Line Interview Answer

“Rest parameters allow functions to accept multiple values as a single array parameter.”

44. What are the rules for rest parameters?*

TypeScript follows specific rules for rest parameters.

Rules for Rest Parameters

1. Only One Rest Parameter Allowed

✅ Correct:

function test(...numbers: number[]) {}

❌ Incorrect:

function test(...a: number[], ...b: number[]) {}

2. Rest Parameter Must Be Last

✅ Correct:

function test(name: string, ...marks: number[]) {}

❌ Incorrect:

function test(...marks: number[], name: string) {}

3. Rest Parameter Is Always an Array

function print(...names: string[]) {
console.log(names);
}

Important Interview Point

Rest parameters improve flexibility in reusable functions.

One-Line Interview Answer

“A function can have only one rest parameter, and it must be the last parameter.”

45. What are anonymous functions in TypeScript?*

Anonymous functions are functions without a name.

They are usually:

  • assigned to variables
  • passed as arguments
  • used as callbacks

Example

let greet = function (): void {
console.log("Hello");
};

Example with Parameters

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

Common Use Cases

  • Callback functions
  • Event handlers
  • Array methods

Example in setTimeout

setTimeout(function () {
console.log("Executed");
}, 1000);

Important Interview Point

Arrow functions are modern alternatives to anonymous functions.

One-Line Interview Answer

“Anonymous functions are functions without names, often stored in variables or used as callbacks.”

46. What are scopes/variable scopes in TypeScript?

Scope defines the accessibility and lifetime of variables in a program.

TypeScript mainly supports:

  • Global Scope
  • Function Scope
  • Block Scope

1. Global Scope

Variables declared outside functions or blocks.

let username = "Jitendra";

Accessible everywhere.

2. Function Scope

Variables declared inside functions.

function test() {
var age = 25;
}

Accessible only inside the function.

3. Block Scope

Variables declared using:

  • let
  • const

inside blocks {}.

if (true) {
let city = "Patna";
}

Accessible only inside the block.

Important Interview Point

  • var → function scope
  • let and const → block scope

Interview Tip

Interviewers frequently ask:

“Difference between var, let, and const scope.”

One-Line Interview Answer

“Scope determines where variables can be accessed in a TypeScript program.”

*47. What are interfaces in TypeScript?

Interfaces define the structure or contract of an object.

They specify:

  • properties
  • methods
  • data types

without implementing them.

Syntax

interface InterfaceName {
property: type;
}

Example

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

let employee: User = {
id: 101,
name: "Jitendra"
};

Interface with Function

interface MathOperation {
(a: number, b: number): number;
}

Benefits

  • Improves code consistency
  • Enhances maintainability
  • Supports abstraction

Important Interview Point

Interfaces are heavily used in:

  • Angular
  • React props
  • APIs
  • enterprise applications

Difference Between Interface and Type Alias

InterfaceType Alias
Mainly for objectsMore flexible
ExtendableSupports unions

One-Line Interview Answer

“Interfaces define the structure or blueprint of objects in TypeScript.”

*48. What are classes in TypeScript?

Classes are blueprints for creating objects.

TypeScript classes support:

  • properties
  • methods
  • constructors
  • inheritance
  • access modifiers

Syntax

class ClassName {
}

Example

class Employee {
name: string;

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

display(): void {
console.log(this.name);
}
}

Create Object

let emp = new Employee("Jitendra");
emp.display();

Benefits

  • Code reusability
  • Encapsulation
  • Better organization

Important Interview Point

Classes are one of the core OOP features supported by TypeScript.

One-Line Interview Answer

“Classes are templates used to create objects with properties and methods.”

*49. What are access modifiers in TypeScript?

Access modifiers control the accessibility of class members.

TypeScript provides:

  • public
  • private
  • protected

1. public

Accessible from anywhere.

class User {
public name: string = "Jitendra";
}

2. private

Accessible only inside the same class.

class User {
private password: string = "123";
}

3. protected

Accessible:

  • inside class
  • inside derived classes
class Person {
protected age: number = 25;
}

Access Modifier Comparison

ModifierSame ClassChild ClassOutside Class
public✅✅✅
protected✅✅❌
private✅❌❌

Important Interview Point

By default, members are:

public

One-Line Interview Answer

“Access modifiers control the visibility and accessibility of class properties and methods.”

*50. What object-oriented principles are supported by TypeScript?

TypeScript supports all major Object-Oriented Programming (OOP) principles.

Main OOP Principles in TypeScript

PrincipleDescription
EncapsulationHiding internal data
InheritanceReusing parent class properties
PolymorphismSame method behaving differently
AbstractionHiding implementation details

1. Encapsulation

Using access modifiers to protect data.

class User {
private password: string = "123";
}

2. Inheritance

Child class inherits parent properties.

class Animal {
move() {}
}

class Dog extends Animal {}

3. Polymorphism

Method overriding.

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

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

4. Abstraction

Using interfaces or abstract classes.

interface Shape {
area(): number;
}

Important Interview Point

TypeScript provides strong OOP support compared to JavaScript.

One-Line Interview Answer

“TypeScript supports encapsulation, inheritance, polymorphism, and abstraction.”

51. What object-oriented terms are supported by TypeScript?

TypeScript supports most major Object-Oriented Programming (OOP) concepts.

Main OOP Terms Supported in TypeScript

OOP TermDescription
ClassBlueprint for objects
ObjectInstance of a class
EncapsulationHiding internal details
InheritanceReusing parent class features
PolymorphismSame method behaving differently
AbstractionHiding implementation details
InterfaceDefines object structure
ConstructorInitializes object properties
Access ModifiersControls accessibility

Example

class Employee {
constructor(public name: string) {}
}

Important Interview Point

TypeScript provides stronger OOP support than JavaScript because it includes:

  • interfaces
  • access modifiers
  • abstract classes
  • strong typing

One-Line Interview Answer

“TypeScript supports OOP concepts like classes, objects, inheritance, polymorphism, abstraction, and encapsulation.”

*52. What is inheritance in TypeScript?

Inheritance is an OOP feature where one class acquires properties and methods of another class.

It promotes:

  • code reusability
  • hierarchical relationships

Syntax

class Child extends Parent {
}

Example

class Animal {
move(): void {
console.log("Moving");
}
}

class Dog extends Animal {
bark(): void {
console.log("Barking");
}
}

Create Object

let dog = new Dog();

dog.move();
dog.bark();

Benefits

  • Reduces duplicate code
  • Improves maintainability
  • Supports reusability

Types of Inheritance Supported

  • Single inheritance
  • Multilevel inheritance
  • Hierarchical inheritance

(TypeScript does not support multiple class inheritance directly.)

Important Interview Point

TypeScript uses the extends keyword for inheritance.

One-Line Interview Answer

“Inheritance allows a child class to reuse properties and methods of a parent class.”

*53. What is method overriding in TypeScript?

Method overriding occurs when a child class provides its own implementation of a parent class method.

Example

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

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

Output

let dog = new Dog();
dog.sound();

Result:

Bark

Benefits

  • Supports runtime polymorphism
  • Allows customized behavior
  • Improves flexibility

Important Interview Point

The child method must have:

  • same name
  • same parameters
  • compatible return type

One-Line Interview Answer

“Method overriding allows a child class to redefine a parent class method.”

54. What are getters and setters in TypeScript?

Getters and setters are special methods used to:

  • read object properties
  • update object properties safely

They provide controlled access to class data.

Getter

Used to retrieve values.

Setter

Used to modify values.

Example

class Employee {
private _salary: number = 0;

get salary(): number {
return this._salary;
}

set salary(value: number) {
this._salary = value;
}
}

Usage

let emp = new Employee();

emp.salary = 50000;

console.log(emp.salary);

Benefits

  • Data encapsulation
  • Validation before assignment
  • Controlled property access

Important Interview Point

Getters and setters are commonly used with private variables.

One-Line Interview Answer

“Getters and setters provide controlled access to class properties.”

55. Can we create immutable/read-only object properties?

Yes. TypeScript allows creating immutable or read-only properties using the readonly modifier.

Once initialized, readonly properties cannot be modified.

Example

class User {
readonly id: number = 101;
}

Invalid Modification

user.id = 200;

This causes an error.

Interface Example

interface Employee {
readonly empId: number;
}

Benefits

  • Prevents accidental modifications
  • Improves data safety
  • Useful for constants and IDs

Important Interview Point

Readonly properties can only be assigned:

  • during declaration
  • inside constructor

One-Line Interview Answer

“Yes, immutable properties can be created using the readonly modifier.”

*56. What is the readonly modifier in TypeScript?

The readonly modifier makes a property immutable after initialization.

Once assigned, the value cannot be changed.

Syntax

readonly propertyName: type;

Example

class Employee {
readonly company: string = "OpenAI";
}

Invalid Operation

employee.company = "Google";

This produces an error.

Readonly in Constructor

class User {
readonly id: number;

constructor(id: number) {
this.id = id;
}
}

Benefits

  • Data protection
  • Prevents accidental updates
  • Improves code reliability

Important Interview Point

Readonly variables differ from const:

  • const → variable immutable
  • readonly → object property immutable

One-Line Interview Answer

“The readonly modifier prevents modification of class or object properties after initialization.”

57. What is JSX in TypeScript?

JSX stands for:

JavaScript XML

It is a syntax extension that allows writing HTML-like code inside JavaScript or TypeScript.

JSX is mainly used with React Official Website.

Example

const element = <h1>Hello TypeScript</h1>;

Why JSX Is Used

  • Easier UI development
  • Cleaner component structure
  • Better readability

JSX in TypeScript

TypeScript supports JSX using:

.tsx

files.

Important Interview Point

JSX is not valid HTML or JavaScript directly.
It gets compiled into JavaScript function calls.

One-Line Interview Answer

“JSX is an XML-like syntax used with React to create UI components inside TypeScript.”

*58. What is the difference between .ts and .tsx files?

Both .ts and .tsx are TypeScript files, but they serve different purposes.

Difference Table

.ts.tsx
Normal TypeScript fileTypeScript + JSX
No JSX supportSupports JSX
Used for logic/codeUsed for React components
Cannot contain HTML-like syntaxCan contain JSX syntax

Example of .ts

let age: number = 25;

Example of .tsx

const App = () => {
return <h1>Hello</h1>;
};

Important Interview Point

Use:

  • .ts → normal TypeScript
  • .tsx → React components with JSX

One-Line Interview Answer

“.ts files contain TypeScript code, while .tsx files contain TypeScript with JSX syntax.”

59. What JSX modes are supported by TypeScript?*

TypeScript supports multiple JSX compilation modes through the jsx option in tsconfig.json.

Common JSX Modes

ModeDescription
reactOld React JSX transform
react-jsxNew React 17+ transform
react-jsxdevDevelopment mode
preserveKeeps JSX unchanged
react-nativeUsed for React Native

Example

{
"compilerOptions": {
"jsx": "react-jsx"
}
}

Commonly Used Mode

Modern React projects mostly use:

react-jsx

Important Interview Point

react-jsx was introduced with React 17 to avoid importing React manually in every file.

One-Line Interview Answer

“TypeScript supports JSX modes like react, react-jsx, preserve, and react-native.”

*60. What are modules in TypeScript?

Modules are reusable files that contain:

  • variables
  • functions
  • classes
  • interfaces

Modules help organize code into smaller, maintainable parts.

Why Modules Are Used

  • Avoid global scope pollution
  • Improve maintainability
  • Enable code reuse

Export Example

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

Import Example

import { add } from "./math";

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

Types of Modules

Module TypeDescription
Internal ModulesOld namespace-based modules
External ModulesFile-based modern modules

Benefits

  • Better code organization
  • Reusability
  • Easier maintenance

Important Interview Point

Modern TypeScript applications mainly use:

  • ES Modules
  • import/export syntax

One-Line Interview Answer

“Modules are reusable TypeScript files that organize code using import and export statements.”

*61. What are namespaces in TypeScript?

Answer

Namespaces are a way to organize related code into a single logical group.

They help avoid:

  • naming conflicts
  • global scope pollution

Namespaces were commonly used before ES modules became popular.

Syntax

namespace NamespaceName {
}

Example

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

Access Namespace Members

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

Important Points

  • Use export to access namespace members outside.
  • Mainly used in older TypeScript projects.

Important Interview Point

Modern applications usually prefer:

  • ES Modules
    instead of namespaces.

One-Line Interview Answer

“Namespaces group related code together and help avoid naming conflicts.”

62. What are internal and external modules?

TypeScript modules are categorized into:

  • Internal Modules
  • External Modules

1. Internal Modules

Internal modules are based on:

namespace

syntax.

Example

namespace App {
export class User {}
}

Characteristics

  • Used within same application
  • Older approach
  • Helps organize code

2. External Modules

External modules are file-based modules using:

  • import
  • export

Example

math.ts

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

app.ts

import { add } from "./math";

Characteristics

  • Modern approach
  • Recommended in large applications
  • Works with ES Modules/CommonJS

Difference Table

Internal ModulesExternal Modules
Uses namespaceUses import/export
Older approachModern approach
Single application scopeFile-based scope

Important Interview Point

Namespaces are now less preferred compared to external modules.

One-Line Interview Answer

“Internal modules use namespaces, while external modules use import/export statements.”

63. What is parameter destructuring in TypeScript?

Parameter destructuring allows extracting object or array values directly inside function parameters.

It improves:

  • readability
  • cleaner code
  • easier property access

Object Destructuring Example

function printUser({ name, age }: { name: string; age: number }) {
console.log(name, age);
}

Function Call

printUser({ name: "Jitendra", age: 25 });

Array Destructuring Example

function display([x, y]: [number, number]) {
console.log(x, y);
}

Benefits

  • Cleaner syntax
  • Reduces repeated property access
  • Useful in React and APIs

Important Interview Point

Parameter destructuring is heavily used in:

  • React props
  • API handling
  • configuration objects

One-Line Interview Answer

“Parameter destructuring extracts object or array values directly in function parameters.”

64. What is noImplicitAny in TypeScript?

noImplicitAny is a TypeScript compiler option that prevents variables or parameters from automatically getting the any type.

It improves type safety.

Example Without noImplicitAny

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

Here:

  • a and b become any

Enable noImplicitAny

{
"compilerOptions": {
"noImplicitAny": true
}
}

Result

TypeScript will show an error:

Parameter 'a' implicitly has an 'any' type

Benefits

  • Better type safety
  • Reduces runtime bugs
  • Encourages explicit typing

Important Interview Point

noImplicitAny is part of:

strict mode

One-Line Interview Answer

“noImplicitAny prevents TypeScript from assigning implicit any types.”

65. How do you debug a TypeScript file?

TypeScript files are usually debugged using:

  • source maps
  • browser developer tools
  • IDE debuggers

Common Debugging Steps

1. Enable Source Maps

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

2. Compile TypeScript

tsc

3. Run Application

node app.js

OR run in browser.

4. Use Debugger

You can debug using:

  • Chrome DevTools
  • VS Code debugger

Example

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

Important Interview Point

Source maps allow debugging original TypeScript instead of generated JavaScript.

One-Line Interview Answer

“TypeScript debugging is commonly done using source maps and browser or IDE debugging tools.”

66. Can multiple .ts files be combined into one .js file?*

Yes. Multiple TypeScript files can be combined into a single JavaScript file using the outFile compiler option.

Example tsconfig.json

{
"compilerOptions": {
"outFile": "./dist/app.js"
}
}

Compilation

tsc

Important Points

  • Mainly works with:
    • AMD modules
    • System modules
  • Not commonly used with modern ES modules.

Benefits

  • Reduces number of output files
  • Simplifies deployment

Important Interview Point

Modern projects mostly use:

  • bundlers like Webpack/Vite
    instead of outFile.

One-Line Interview Answer

“Yes, multiple .ts files can be merged into one .js file using the outFile option.”

*67. What is Type Assertion in TypeScript?

Type Assertion tells TypeScript to treat a value as a specific type.

It is used when the developer knows more about the type than TypeScript.

Syntax

Angle-Bracket Syntax

let value = <string>data;

as Syntax

let value = data as string;

Example

let data: any = "Hello";

let length: number = (data as string).length;

Important Points

  • Type assertion does not change runtime behavior.
  • It only affects TypeScript type checking.

Benefits

  • Better type handling
  • Useful with DOM elements
  • Helps with dynamic data

Important Interview Point

Type assertion is not type casting in JavaScript runtime.

One-Line Interview Answer

“Type assertion tells TypeScript to treat a value as a specific type.”

*68. What is the “as” syntax in TypeScript?

The as syntax is a modern way to perform type assertion in TypeScript.

It is preferred over angle-bracket syntax.

Syntax

value as Type

Example

let data: any = "TypeScript";

let length = (data as string).length;

DOM Example

let input = document.getElementById("username") as HTMLInputElement;

Why Preferred?

  • Cleaner syntax
  • Works better with JSX/React
  • More readable

Important Interview Point

In .tsx files:

  • angle-bracket assertions may conflict with JSX syntax
  • therefore as is preferred

One-Line Interview Answer

“The as syntax is the preferred way to perform type assertions in TypeScript.”

*69. How do you check null and undefined values?

TypeScript provides multiple ways to check null and undefined values.

1. Using Equality Operators

if (value == null) {
console.log("Null or Undefined");
}

2. Strict Comparison

if (value === undefined) {
console.log("Undefined");
}

3. Optional Chaining

user?.name

4. Nullish Coalescing Operator

let result = value ?? "Default";

Example

let username: string | null = null;

if (username !== null) {
console.log(username);
}

Important Interview Point

Modern TypeScript commonly uses:

  • optional chaining ?.
  • nullish coalescing ??

One-Line Interview Answer

“Null and undefined values are checked using comparison operators, optional chaining, and nullish coalescing.”

*70. Does TypeScript support function overloading?

Yes. TypeScript supports function overloading.

Function overloading allows multiple function signatures with:

  • different parameters
  • different types

while sharing a single 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;
}

Function Calls

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

Important Rules

  • Multiple declarations allowed
  • Only one implementation function
  • Implementation must handle all cases

Benefits

  • Better readability
  • Strong type checking
  • Flexible APIs

Important Interview Point

TypeScript supports:

  • compile-time overloading
    not runtime overloading like Java.

One-Line Interview Answer

“TypeScript supports function overloading by defining multiple function signatures with one implementation.”


Previous Tutorial
MongoDB Advanced
Next Tutorial
TypeScript for Intermediate
ExamAdda LogoExamAdda Tech

Your comprehensive destination for learning programming, web development, data science, and modern technologies. Master coding with our in-depth tutorials and practical examples.

Support

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of Service

Connect With Us

Follow us on social media for the latest tutorials, tips, and programming updates.

© 2026 ExamAdda Tech. All rights reserved.

Privacy PolicyTerms of ServiceCookie Policy