TypeScript Interview Questions and Answers

Last Updated : 27 Jul, 2026

TypeScript is a statically typed superset of JavaScript developed by Microsoft. It adds static typing and modern JavaScript features to improve code quality, scalability, and maintainability. Widely used by companies like Microsoft, Meta, LinkedIn, and Evernote, it helps developers catch errors early and build reliable applications.

1. Explain the data types available in TypeScript.

TypeScript provides two categories of data types:

1. Built-in Data Types:

  • string: Stores text values.
  • number: Stores numeric values.
  • boolean: Stores true or false.
  • null: Represents an empty value.
  • undefined: Represents an uninitialized variable.
  • any: Accepts values of any type.
  • unknown: Stores unknown values safely.
  • void: Used for functions that return no value.
  • never: Used for functions that never return.

2. User-defined Data Types:

  • Array: Stores multiple values of the same type.
  • Tuple: Stores fixed-size values of different types.
  • Enum: Defines a set of named constants.
  • Class: Creates objects with properties and methods.
  • Interface: Defines the structure of an object.
  • Type Alias: Creates a custom name for a type.

2. In how many ways we can declare variables in TypeScript?

TypeScript provides three ways to declare variables:

  • var: Function-scoped. It can be redeclared and updated. Generally not recommended in modern TypeScript.
  • let: Block-scoped. It can be updated but cannot be redeclared within the same scope.
  • const: Block-scoped. It cannot be reassigned after initialization.
var name = "John";
let age = 25;
const country = "India";

3. How you can declare a explicit variables in Typescript?

You can declare an explicitly typed variable by specifying its data type after the variable name using a colon (:).

Syntax:

let variableName: dataType = value;

Example:

let companyName: string = "GeeksforGeeks";

companyName = "Cricket"; // Valid
companyName = 28; // Error: Type 'number' is not assignable to type 'string'

This ensures type safety by allowing only values of the declared data type.

4. How to declare a function with typed annotation in TypeScript?

In TypeScript, you can declare a function by specifying the types of its parameters and its return type.

Example:

function getDetails(name: string, age: number): string {
return `My name is ${name} and my age is ${age}.`;
}

console.log(getDetails("Emrit", 22)); // Valid
console.log(getDetails("Neha", "18")); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.

5. Describe the "any" type in TypeScript.

The any type allows a variable to hold a value of any data type, disabling TypeScript's type checking for that variable. It is useful when the type of data is unknown, such as data received from an API or user input.

Example:

let studentData = `{
"studentName": "Aakash",
"studentID": 12345,
"studentCourse": "B.Tech"
}`;

let student: any = JSON.parse(studentData);

console.log(student.studentName);

6. What are the advantages of using TypeScript?

Some key advantages of TypeScript are:

  • Static Typing: Detects type-related errors at compile time.
  • Compiles to JavaScript: Runs in all modern browsers and JavaScript environments.
  • Better IDE Support: Provides IntelliSense, auto-completion, and code navigation.
  • Improved Code Maintainability: Makes large applications easier to read and maintain.
  • Easy Refactoring: Helps safely rename variables, methods, and classes.
  • Supports Modern JavaScript Features: Includes the latest ECMAScript features with backward compatibility.
  • Better Scalability: Ideal for developing large and enterprise-level applications.

7. List some disadvantages of using TypeScript.

Some disadvantages of TypeScript are:

  • Compilation Required: TypeScript must be transpiled into JavaScript before execution.
  • Longer Build Time: Compilation can increase build time, especially in large projects.
  • Learning Curve: Developers need to learn TypeScript's type system and additional features.
  • Additional Configuration: Setting up tsconfig.json and build tools adds complexity.
  • Type Definitions: Some third-party libraries may require separate type definition packages (@types) if they don't include their own types.

8. Explain the void type in TypeScript.

The void type represents the absence of a return value. It is primarily used as the return type of functions that do not return any value.

Example:

function favGame(): void {
console.log("My favourite game is Cricket.");
}

favGame();

9. What is type null and its use in TypeScript?

The null type represents the intentional absence of a value. It is commonly used to indicate that a variable or object currently has no value. In TypeScript, null is typically used with union types (e.g., string | null).

Example:

function getData(orgName: string | null): void {
if (orgName === null) {
console.log("No organization name provided.");
} else {
console.log(orgName);
}
}

getData(null);
getData("GeeksforGeeks");

10. Describe the syntax for creating objects in TypeScript.

An object in TypeScript is a collection of key-value pairs, where each property has a defined type.

Example:

const myObj: { name: string; desc: string } = {
name: "GeeksforGeeks",
desc: "A Computer Science Portal",
};

console.log(myObj);

11. Can we specify the optional properties to TypeScript Object, if Yes, explain How?

Yes. TypeScript allows you to define optional properties in an object using the ? operator. Optional properties are not required when creating the object.

Example:

const myObj: { name: string; desc: string; est?: number } = {
name: "GeeksforGeeks",
desc: "A Computer Science Portal",
};

console.log(myObj);

myObj.est = 2008;
console.log(myObj);

12. Explain the undefined type in TypeScript.

The undefined type represents a variable that has been declared but not assigned a value. It is also used for optional properties and function parameters that are not provided.

13. Explain the behavior of arrays in TypeScript.

TypeScript arrays are JavaScript arrays with static type checking. By default, an array stores elements of the specified type, and TypeScript reports a compile-time error if a value of a different type is added.

Example:

const numbers: number[] = [1, 23, 28, 56];

console.log(numbers);

numbers.push("GeeksforGeeks"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.

14. How can you compile a TypeScript file?

To compile a TypeScript file, you use the tsc (TypeScript Compiler) command. You can compile a TypeScript file by running:

tsc filename.ts

This command compiles the .ts file into a .js (JavaScript) file. Make sure to have TypeScript installed globally or locally in your project for this to work.

15. Differentiate between the .ts and .tsx file extensions given to the TypeScript file.

.ts

.tsx

Contains only TypeScript code.

Contains TypeScript code with JSX syntax.

Used for utility functions, classes, interfaces, services, and other non-UI logic.

Primarily used for React components that return JSX.

Does not support JSX.

Supports JSX and TypeScript together.

16. What is "in" operator and why it is used in TypeScript?

The in operator is used to check whether a property exists in an object. It returns true if the property is present; otherwise, it returns false. It is also commonly used for type narrowing when working with union types.

const person = {
name: "John",
age: 25,
};

console.log("name" in person); // true
console.log("city" in person); // false

17. Explain the union types in TypeScript?

A union type allows a variable, parameter, or property to hold one of multiple specified types. It is defined using the pipe (|) operator.

let variableName: type1 | type2;

18. Explain type alias in TypeScript?

A type alias is used to create a custom name for an existing type. It does not create a new type; it simply provides a more meaningful and reusable name for a type.

type TypeName = ExistingType;

19. Is TypeScript strictly statically typed language?

No. TypeScript is an optionally statically typed language. It supports static typing, but developers can choose whether to explicitly specify types or rely on type inference. Additionally, the any type can be used to disable type checking for a variable.

20. Is template literal supported by TypeScript?

Yes. TypeScript supports template literals, just like JavaScript. They use backticks (`) and allow you to embed expressions or variables inside strings using the ${} syntax. They also support multi-line strings.

21. How to declare a arrow function in TypeScript?

An arrow function in TypeScript is declared using the same syntax as JavaScript. You can optionally specify the types of its parameters and return type using type annotations.

Example:

const typedArrowFunc = (orgName: string, desc: string): string => {
return `Organization: ${orgName}, Description: ${desc}`;
};

console.log(typedArrowFunc("GeeksforGeeks", "A Computer Science Portal"));

22. How to define a function which accepts the optional parameters?

You can define an optional parameter by adding the ? operator after the parameter name. Optional parameters are not required when calling the function and must be placed after required parameters.

Example:

function cricketer(name: string, runs?: number): void {
if (runs === undefined) {
console.log(`Cricketer Name: ${name}, Runs Scored: Not Available`);
} else {
console.log(`Cricketer Name: ${name}, Runs Scored: ${runs}`);
}
}

cricketer("Virat Kohli", 26000);
cricketer("Yuzvendra Chahal");

23. Explain noImplicitAny in TypeScript.

noImplicitAny is a compiler option in tsconfig.json that prevents TypeScript from assigning the any type implicitly. When enabled, the compiler reports an error if a variable or parameter has an inferred any type.

Example:

function greet(name) {
console.log(name);
}

With noImplicitAny: true, the above code produces an error because name implicitly has the any type.

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

24. What are interfaces in TypeScript?

An interface in TypeScript defines the structure (contract) that an object or class must follow. It specifies the properties and methods without providing their implementation. Interfaces are declared using the interface keyword.

25. In how many ways you can use the for loop in TypeScript?

TypeScript supports the following ways to iterate over data:

  • for loop: Used when you need an index or a fixed number of iterations.
  • for...of loop: Iterates over the values of an iterable, such as an array or string.
  • for...in loop: Iterates over the keys or property names of an object.
  • forEach() method: An array method that executes a callback function for each element.
// for loop
for (let i = 0; i < 3; i++) { }

// for...of
for (const item of myArray) { }

// for...in
for (const key in myObject) { }

// forEach()
myArray.forEach((item) => { });

26. What is never type and its uses in TypeScript?

The never type represents values that never occur. It is used for functions that never return normally, such as functions that always throw an error or run in an infinite loop. Unlike void, a never function does not return any value.

Example:

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

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

27. Explain the working of enums in TypeScript?

An enum is a TypeScript feature used to define a collection of named constants. Enums improve code readability by assigning meaningful names to constant values. TypeScript supports both numeric and string enums.

By default, numeric enum values start from 0 and increment by 1, but you can specify a custom starting value.

Example:

enum DemoEnum {
Milk = 1,
Curd,
Butter,
Cheese,
}

let item: DemoEnum = DemoEnum.Butter;

console.log(item); // 3

28. Explain the parameter destructuring in TypeScript.

Parameter destructuring allows you to extract object properties directly in the function parameter list instead of accessing them inside the function body. It makes the code cleaner and more readable.

function getOrganisation(
{ orgName, orgDesc }: { orgName: string; orgDesc: string }
) {
console.log(`Organization: ${orgName}, Description: ${orgDesc}`);
}

getOrganisation({
orgName: "GeeksforGeeks",
orgDesc: "A Computer Science Portal",
});

29. Explain type inference in TypeScript.

Type inference is the process by which TypeScript automatically determines the type of a variable, parameter, or function return value based on the assigned value. This reduces the need for explicit type annotations while maintaining type safety.

let name = "John";   // Inferred as string
let age = 25; // Inferred as number
let isAdmin = true; // Inferred as boolean

30. What are modules in TypeScript?

Modules are used to organize code into separate files, making it easier to manage, reuse, and maintain. A module can export functions, classes, interfaces, types, variables, or constants, which can be imported into other files using the import statement.

Example:

// math.ts
export function multiply(a: number, b: number): number {
return a * b;
}
// app.ts
import { multiply } from "./math";

console.log(multiply(5, 4));

31. In how many ways you can classify Modules?

In modern TypeScript, modules are based on the ES Module system. A file becomes a module if it contains at least one import or export statement.

There are two commonly used module systems:

  • ES Modules (ESM): The standard module system in modern TypeScript. Uses the import and export keywords and is recommended for new projects.
  • CommonJS Modules: Uses require() and module.exports. It is mainly used in older Node.js projects and for compatibility.

32. What is the use of tsconfig.json file in TypeScript?

The tsconfig.json file is the configuration file for a TypeScript project. It specifies the compiler options and controls how the TypeScript compiler (tsc) compiles the project.

Some common configurations include:

  • Compiler options: Target JavaScript version, module system, strict mode, output directory, etc.
  • Project settings: Specify which files or folders to include or exclude from compilation.
  • Project root: Marks the directory as the root of the TypeScript project.

33. What are Decorators in TypeScript?

Decorators are a special syntax used to add metadata or modify the behavior of classes and class members, such as methods, properties, accessors, and parameters. They are declared using the @ symbol and are commonly used in frameworks like Angular and NestJS.

function Logger(target: Function) {
console.log("Class created:", target.name);
}

@Logger
class Person {}

34. How to debug a TypeScript file?

A TypeScript file can be debugged using source maps, which map the generated JavaScript code back to the original TypeScript code. Source maps can be generated using the --sourceMap compiler option or by enabling "sourceMap": true in the tsconfig.json file.

tsc --sourceMap script.ts

This generates:

  • script.js
  • script.js.map

These files allow debuggers such as VS Code or browser Developer Tools to debug the original TypeScript source.

35. Describe anonymous functions and their uses in TypeScript?

An anonymous function is a function without a name. It is commonly used as a callback function, especially for event handling, timers, and array methods.

Example:

myBtn.addEventListener("click", function () {
console.log("Button clicked");
});

36. Is it possible to call the constructor function of the base class using the child class?

Yes. In TypeScript, a child class can call the base class constructor using the super() method. If the base class constructor accepts parameters, they must be passed to super(). The super() call must be made before using this in the child class constructor.

37. How to combine multiple TypeScript files and convert them into single JavaScript file?

TypeScript provides the --outFile compiler option to combine multiple TypeScript files into a single JavaScript file. This option is mainly used with amd or system module formats and is not supported with modern ES Modules.

tsc --outFile combined.js script1.ts script2.ts script3.ts

38. Explain type of operator in TypeScript and where to use it.

The typeof operator is used to determine the type of a value at runtime. In TypeScript, it can also be used in type annotations to reuse the type of an existing variable.

Example:

const strVar = "GeeksforGeeks";
const numVar = 28;

console.log(typeof strVar); // "string"
console.log(typeof numVar); // "number"

const strVar2: typeof strVar = "Cricket";
const numVar2: typeof numVar = 25;

39. How you can compile a TypeScript file?

TypeScript code cannot be executed directly. It must first be compiled (transpiled) into JavaScript using the TypeScript Compiler (tsc).

tsc script.ts

40. Which principles of Object Oriented Programming are supported by TypeScript?

TypeScript supports all four fundamental OOP principles:

  • Abstraction: Hides implementation details and exposes only essential functionality using abstract classes and interfaces.
  • Encapsulation: Restricts direct access to data using access modifiers such as public, private, and protected.
  • Inheritance: Allows a class to inherit properties and methods from another class using the extends keyword.
  • Polymorphism: Allows the same method or interface to have different implementations through method overriding and interfaces.

41. Explain Mixins in TypeScript

Mixins are a way to reuse functionality across multiple classes. They allow a class to combine behaviors from multiple sources without using multiple inheritance. A mixin is typically implemented as a function that takes a class and returns a new class with additional functionality.

42. Is it possible to create the immutable Object properties in TypeScript?

Yes. TypeScript allows you to make object properties immutable by using the readonly keyword. A readonly property can only be assigned a value during object initialization or in a class constructor. Any attempt to reassign it later results in a compile-time error.

TypeScript Interview Questions For Experienced

43. In what situation you should use a class and a interface?

Use an interface when you want to define the structure or contract of an object or class without providing an implementation. It is commonly used for type checking and enforcing a consistent shape.

Use a class when you need to create objects with properties, methods, constructors, and implementations. Classes also support OOP features such as encapsulation, inheritance, abstraction, and polymorphism.

44. What are the differences between the classes and the interfaces in TypeScript?

Class

Interface

Declared using the class keyword.

Declared using the interface keyword.

Contains both declarations and implementations.

Contains only property and method declarations.

Can have constructors, access modifiers, and method implementations.

Cannot have constructors or method implementations.

Used to create objects.

Used to define the structure (contract) of objects or classes.

Supports inheritance using extends.

Can be extended by other interfaces and implemented by classes.

45. How to declare a class in TypeScript?

A class in TypeScript is declared using the class keyword. It can contain properties, constructors, and methods, all of which can have type annotations.

Example:

class Cricketer {
name: string;
runs: number;

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

updateRuns(): number {
this.runs += 139;
return this.runs;
}
}

46. How the inheritance can be used in TypeScript?

Inheritance is an OOP feature that allows a child class to inherit the properties and methods of a parent class. It is implemented using the extends keyword. The child class can also add new members or override inherited methods.

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

class Employee extends Person {
constructor(name: string, public id: number) {
super(name);
}
}

const emp = new Employee("John", 101);

47. What are the different ways for controlling the visibility of member data?

TypeScript provides three access modifiers to control the visibility of class members:

  • public: The default access modifier. Members can be accessed from anywhere in the program.
  • private: Members can only be accessed within the same class. They are not accessible outside the class or by derived classes.
  • protected: Members can be accessed within the same class and by its derived (child) classes, but not from outside the class.

48. How to convert a .ts file into TypeScript Definition file?

You can generate a TypeScript declaration file (.d.ts) using the --declaration compiler option. The declaration file contains only type information (such as interfaces, classes, functions, and type definitions) without the implementation.

Command:

tsc --declaration script.ts

This command generates:

  • script.js
  • script.d.ts

49. Is it possible to create the static classes in TypeScript?

No. TypeScript does not support static classes like C#. However, it does support static members (properties and methods) inside a class using the static keyword.

For utility functions or constants, TypeScript typically uses modules or top-level exports instead of static classes.

50. Explain conditional typing in TypeScript?

Conditional types allow you to select one type or another based on a condition. They use a syntax similar to the ternary operator and are evaluated at compile time.

Comment

Explore