52+ Top TypeScript Interview Questions and Answers for All Skill Levels in 2025
Updated on Feb 24, 2025 | 36 min read | 1.1k views
Share:
For working professionals
For fresh graduates
More
Updated on Feb 24, 2025 | 36 min read | 1.1k views
Share:
Table of Contents
TypeScript is a statically typed superset of JavaScript that adds type safety and powerful tooling features to the language. It is widely used in front-end frameworks like Angular, React, and Vue, as well as in back-end development with Node.js.
By tackling TypeScript interview questions on concepts like mapping types and static typing, you can improve your chances of landing roles such as a front-end developer. This post covers key TypeScript interview topics across all skill levels, providing valuable insights and examples.
The core TypeScript interview questions will focus on aspects like data types, syntax, functions, and essential concepts like getters and setters.
Here are some core TypeScript interview questions and answers.
1. What is the definition of TypeScript?
A: TypeScript is an open-source statically typed superset of JavaScript developed by Microsoft. It extends JavaScript by adding static types, generics, interfaces, and modern ECMAScript features, making it more scalable for large applications.
Since TypeScript compiles to plain JavaScript, it can run in any environment that supports JavaScript. It is used in frameworks like Angular, React, Vue.js, and Node.js to build complex web applications with better structure and safety.
2. How are Arrays defined and used in TypeScript?
A: Arrays in TypeScript are used similarly to JavaScript arrays but with added type safety. They can be declared using bracket notation (type[]) or generic syntax (Array<type>).
let numbers: number[] = [10, 20, 30];
numbers.push(40); // Works fine
numbers.push("fifty"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.
let colors: Array<string> = ["Red", "Green", "Blue"];
colors.push("Yellow"); // Allowed
TypeScript also supports tuples, a specialized type of array where each element has a fixed type:
let user: [string, number] = ["Raj", 30]; // First element must be a string, second must be a number
Also Read: What Is an Array? Understanding the Array Meaning, Types, and Practical Applications
3. What are some key applications of TypeScript?
A: TypeScript is widely used in software development due to its strong type system, tooling support, and scalability.
Here are some key applications:
Learn the latest languages, such as JavaScript, to create web applications for roles like web developer. Enroll in upGrad’s Online Software Development Courses now!
4. What are the benefits of using TypeScript?
A: The benefits of TypeScript include better code maintainability, static typing, and improved debugging.
Here are the benefits of using TypeScript:
5. What are the drawbacks of using TypeScript?
A: Increase in complexity, a steep learning curve, and compilation overhead are some main drawbacks of using TypeScript.
Here are the drawbacks:
6. What are the key features of Arrays in TypeScript?
A: TypeScript arrays have several built-in features like tuple support and type safety, making them more powerful and type-safe than JavaScript arrays.
Here are the features of Arrays:
7. How do you declare variables in TypeScript?
A: Variables are declared in TypeScript using let, const, or var, similar to JavaScript. However, TypeScript allows explicit type annotations, ensuring type safety and preventing unintended assignments.
Here’s how you declare variables:
Example:
let age: number = 25;
age = 30; // Allowed
age = "thirty"; // Error: Type 'string' is not assignable to type 'number'
Example:
const name: string = "Alice";
name = "Bob"; // Error: Cannot assign to 'name' because it is a constant.
Example:
var greeting: string = "Hello";
8. What access modifiers are available in TypeScript?
A: Access modifiers are used to enforce encapsulation and data security in TypeScript applications.
Here are the access modifiers available:
Example:
class Person {
public name: string;
constructor(name: string) {
this.name = name;
}
}
const user = new Person("Alice");
console.log(user.name); // Accessible
Example:
class BankAccount {
private balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
}
const account = new BankAccount(1000);
console.log(account.balance); // Error: Property 'balance' is private.
Example:
class Vehicle {
protected speed: number = 0;
}
class Car extends Vehicle {
increaseSpeed() {
this.speed += 10; // Allowed in subclass
}
}
const myCar = new Car();
myCar.speed = 50; // Error: Property 'speed' is protected.
9. How do Loops work in TypeScript?
A: Loops in TypeScript allow you to iterate over collections or execute code multiple times. Commonly used loops are for, while, and do-while.
Here’s how loops work:
Example:
for (let i = 0; i < 5; i++) {
console.log(i); // Prints numbers 0 to 4
}
Example:
let count = 0;
while (count < 3) {
console.log("Hello"); // Prints "Hello" three times
count++;
}
Example:
let num = 10;
do {
console.log(num); // Runs once even though num is greater than 5
} while (num < 5);
Example:
let fruits = ["Apple", "Banana", "Cherry"];
for (let fruit of fruits) {
console.log(fruit); // Prints each fruit
}
Example:
let person = { name: "Raj", age: 25 };
for (let key in person) {
console.log(key, person[key as keyof typeof person]); // Prints property names and values
}
10. What purpose does the tsconfig.json file serve?
A: The tsconfig.json file is the configuration file that defines compiler options, file inclusions, and project settings to control TypeScript compilation.
Key purposes include:
Example:
{
"compilerOptions": {
"target": "ES6",
"strict": true,
"outDir": "./dist",
"module": "CommonJS"
},
"include": ["src"],
"exclude": ["node_modules"]
}
11. How can a string be converted into a number in TypeScript?
A: The right method to convert depends on whether the number is an integer or floating-point value.
The commonly used methods include:
Example:
let num = parseInt("42.9");
console.log(num); // Output: 42
Example:
let num = parseFloat("42.9");
console.log(num); // Output: 42.9
Example:
let num = Number("42.9");
console.log(num); // Output: 42.9
Example:
let num = +"42.9";
console.log(num); // Output: 42.9
12. What is contextual typing in TypeScript?
A: Contextual typing feature automatically infers types based on context rather than requiring explicit annotations.
It improves code clarity, reduces redundancy, and enhances developer experience.
Example: Inferring function parameters:
let printMessage = (msg: string) => {
console.log(msg);
};
Here, TypeScript infers that msg must be a string, so an explicit type declaration is unnecessary.
13 What is JSX and how does it relate to TypeScript?
A: JSX (JavaScript XML) is a syntax extension used in React that allows you to write HTML-like structures within JavaScript or TypeScript.
It improves code readability and enables you to define UI components more declaratively. JSX elements are compiled into standard JavaScript using tools like Babel.
TypeScript can also compile JSX directly without needing Babel if the appropriate jsx option is set in tsconfig.json.
In TypeScript, JSX can be used by setting the jsx option in tsconfig.json. TypeScript improves JSX by adding strict type-checking to component props, improving error detection.
Example:
type ButtonProps = {
label: string;
};
const Button: React.FC<ButtonProps> = ({ label }) => {
return <button>{label}</button>;
};
export default Button;
14. What is static typing and how is it implemented in TypeScript?
A: Static typing allows you to determine variable types at compile time rather than runtime, preventing type-related errors before execution. It reduces runtime errors, improves code maintainability, and enhances development efficiency.
JavaScript itself doesn't have "dynamic typing", as is commonly believed. JavaScript's types are actually dynamic, but not strictly enforced (e.g., type coercion).
Here’s how static typing is used in TypeScript:
Example:
let name: string = "Raj"; // Only allows strings
let age: number = 25; // Only allows numbers
Example:
let isAdmin = true; // Inferred as 'boolean'
Example:
function add(a: number, b: number): number {
return a + b;
}
Example:
let count: number = "ten"; // ❌ Error: Type 'string' is not assignable to 'number'
15. How do the import and export keywords function in TypeScript?
A: The import and export keyword enables modular programming by allowing code to be shared across multiple files, improving reusability.
Here’s how they function:
Exporting Modules: Modules can be exported in two ways:
Example:
export const pi = 3.14;
export function square(num: number): number {
return num * num;
}
Example:
export default function greet(name: string) {
return `Hello, ${name}`;
}
Importing Modules: Modules are imported using the following ways:
Example:
import { pi, square } from "./math";
console.log(square(4)); // Output: 16
Example:
import greet from "./greet";
console.log(greet("Raj")); // Output: Hello, Raj
16. Is it possible to use TypeScript for backend development?
A: TypeScript can be used for backend development, especially with Node.js frameworks like NestJS, Express, and Koa. It improves backend development by providing type safety, code structure, and better debugging features.
Here’s why you must use TypeScript for backend development:
Also Read: What Does a Back-End Developer Do?
17. How can you check if a variable is null or undefined in TypeScript?
A: Checking if the variables are null (explicitly empty) or undefined (declared but not assigned a value) ensures error-free execution. It is especially important when handling user inputs or API responses.
Here’s how you can check:
Example:
if (value === null || value === undefined) {
console.log("Value is either null or undefined");
}
Example:
console.log(user?.name); // Returns 'undefined' instead of throwing an error
Example:
let result = value ?? "Default Value"; // Uses "Default Value" if value is null/undefined
Example:
if (typeof value === "undefined") {
console.log("Value is undefined");
}
18. What are getters and setters in TypeScript?
A: Getters and setters are special class methods used to encapsulate access to private properties, ensuring controlled property modification.
Here’s how they work in TypeScript:
Example:
class Person {
private _age: number = 0;
get age(): number {
return this._age;
}
set age(value: number) {
if (value < 0) {
throw new Error("Age cannot be negative");
}
this._age = value;
}
}
const user = new Person();
user.age = 25; // ✅ Valid
console.log(user.age); // Output: 25
user.age = -5; // ❌ Error: Age cannot be negative
19. How can constants be implemented within a class in TypeScript?
A: Constants are implemented using the readonly keyword or by declaring them as static readonly. The readonly keyword ensures that a property can be assigned only once, either at declaration or in the constructor.
Here’s how you can implement readonly:
Example:
class Car {
readonly brand: string;
constructor(brand: string) {
this.brand = brand; // Allowed in constructor
}
}
Example:
class MathConstants {
static readonly PI = 3.14;
}
console.log(MathConstants.PI); // Output: 3.14
20. What does the Declare keyword mean in TypeScript?
A: The declare keyword informs the compiler about the existence of a variable, function, or module without providing its actual implementation.
It is mainly used for ambient declarations, allowing TypeScript to work with non-TypeScript libraries or global variables.
Here are the different use cases of declare keyword:
Example:
declare var API_URL: string;
console.log(API_URL); // Assumes API_URL exists at runtime
Example:
declare function fetchData(url: string): void;
fetchData("https://api.example.com");
Example:
declare module "someLibrary" {
export function someFunction(): void;
}
21. How do Interfaces function in TypeScript?
A: Interfaces define a contract for object structures, ensuring that objects follow a specific shape. Unlike classes, interfaces do not generate JavaScript code—they are used only for type checking during development.
Here’s how Interface functions in TypeScript:
Example:
interface Person {
name: string;
age: number;
}
const user: Person = { name: "Kumar", age: 30 };
Example:
interface Employee extends Person {
position: string;
}
const employee: Employee = { name: "Bob", age: 40, position: "Manager" };
Also Read: The Ultimate Guide to Interfaces in PHP: Definition, Implementation, and Best Practices for 2025
22. What is the purpose of the ‘as’ syntax in TypeScript?
A: The as keyword is used for type assertions, allowing you to tell TypeScript to treat a value as a specific type. It does not change the actual data but overrides TypeScript’s type inference property.
Here are the use cases of as keyword:
Example:
let value: string | number = "Hello";
let strLength: number = (value as string).length;
console.log(strLength); // Output: 5
TypeScript initially treats value as string | number, so length is not directly accessible. Using as string informs TypeScript that value is a string at that point.
Example:
let input = document.querySelector("#username") as HTMLInputElement;
console.log(input.value); // TypeScript now knows input is an HTMLInputElement
Without as, TypeScript would infer input as Element | null, preventing access to .value.
23. How are Lambda functions defined in TypeScript?
A: Lambda functions define functions in TypeScript using the => syntax. They eliminate the need for the function keyword and automatically bind this.
Syntax of a Lambda function:
const add = (a: number, b: number): number => a + b;
console.log(add(5, 3)); // Output: 8
Example: Using Lamba function with Array:
const numbers = [1, 2, 3, 4];
const squared = numbers.map((num) => num * num);
console.log(squared); // Output: [1, 4, 9, 16]
24. How are objects created in TypeScript?
A: Objects can be created using object literals, interfaces, and classes, each having different use cases.
Here’s how objects are created in TypeScript:
Example:
const user = {
name: "Raj",
age: 30,
greet: () => "Hello!",
};
console.log(user.name); // Output: Raj
Example:
interface Car {
brand: string;
year: number;
}
const myCar: Car = {
brand: "Tesla",
year: 2022,
};
Example:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
const person1 = new Person("Kumar", 40);
console.log(person1.name); // Output: Kumar
Core questions in TypeScript introduce concepts such as object creation, syntax usage, and key features like static typing. Now, let’s explore the TypeScript interview questions for intermediate learners.
Knowledge of intermediate-level concepts like object-oriented principles, modules, namespaces, and advanced data handling is essential for career advancement.
Here are some TypeScript interview questions and answers for intermediate learners.
1. What are the various data types used in TypeScript?
A: TypeScript provides data types that help enforce type safety and improve code maintainability. They can be categorized into primitive types, user-defined types, and special types.
Here are the different data types used:
Example:
let name: string = "Raj";
Example:
let age: number = 25;
Example:
let isLoggedIn: boolean = true;
Example:
let bigValue: bigint = 9007199254740991n;
example:
let id: symbol = Symbol("unique");
Example:
let numbers: number[] = [1, 2, 3];
Example:
let user: [string, number] = ["Kumar", 30];
Example:
enum Direction { Up, Down, Left, Right }
let move: Direction = Direction.Up;
Example:
let person: { name: string; age: number } = { name: "Raj", age: 30 };
Example:
let value: any = "Hello"; // Can be reassigned to any type
Example:
let data: unknown = "TypeScript";
if (typeof data === "string") console.log(data.toUpperCase());
Example:
function logMessage(): void {
console.log("Logging...");
}
Example:
let empty: null = null;
let notAssigned: undefined = undefined;
Example:
function throwError(message: string): never {
throw new Error(message);
}
Also Read: A Comprehensive Guide to Understanding the Different Types of Data
2. What does Type Inference mean in TypeScript?
A: Type inference means that the compiler automatically determines the type of a variable based on its initial value without requiring explicit type annotations. This helps reduce redundant type declarations while maintaining type safety.
Here’s how Type Inference works:
Example:
let message = "Hello"; // Inferred as 'string'
Example:
function add(a: number, b: number) {
return a + b; // Inferred as 'number'
}
Example:
let numbers = [1, 2, 3]; // Inferred as 'number[]'
Example:
document.addEventListener("click", (event) => {
console.log(event.clientX); // 'event' inferred as MouseEvent
});
3. Can you explain Tuples in TypeScript with an example?
A: A tuple is a special array where each element has a fixed type and position. It enables storing multiple values of different types in a structured way.
They can be used for API responses, structured data, and returning multiple values from functions.
Declaring a Tuple in TypeScript:
let user: [string, number] = ["Raj", 30];
console.log(user[0]); // Output: Raj
console.log(user[1]); // Output: 30
Example: Using Optional and Read-only Tuple
let employee: [string, number, boolean?] = ["Ram", 45]; // Optional third element
let config: readonly [number, string] = [404, "Not Found"]; // Read-only tuple
Also Read: What is Tuple in DBMS? Types, Examples & How to Work
4. What is an Anonymous Function in TypeScript?
A: An anonymous function has no name that is usually assigned to a variable or used inline. It is commonly used in callbacks, event handlers, and functional programming.
They can be sued for encapsulating functionality without polluting the global scope.
Example:
const greet = function(name: string): string {
return `Hello, ${name}`;
};
console.log(greet("Raj")); // Output: Hello, Raj
TypeScript also supports arrow functions, which are a shorter syntax for anonymous functions.
Example:
const add = (a: number, b: number) => a + b;
console.log(add(5, 3)); // Output: 8
5. How can TypeScript be installed?
A: You can install TypeScript in two primary ways: globally for system-wide use or locally within a specific project.
Here’s how it can be installed:
npm install -g typescript
npm install --save-dev typescript
Verifying Installation:
tsc --version
6. What are Decorators in TypeScript?
A: Decorators are special functions that modify classes, methods, properties, or parameters at runtime. They are usually used in NestJS, Angular, and metadata-driven frameworks.
Decorators are not officially supported in TypeScript. They are part of the experimental proposal and are still in the "stage 2" proposal under ECMAScript.
In Angular, decorators are used to add metadata to classes, properties, methods, and parameters. They provide information that Angular uses to configure, instantiate, and manage different parts of the application.
Importance of using Decorators:
Example:
function Logger(constructor: Function) {
console.log("Logging...");
}
@Logger
class Person {
constructor(public name: string) {}
}
The @Logger is a decorator that runs when the Person class is instantiated.
7. How do Mixins work in TypeScript?
A: Mixins are a way to combine multiple classes or behaviors into a single class. Unlike inheritance, mixins allow a class to adopt properties and methods from multiple classes.
Mixins facilitate code reuse and improve maintainability by avoiding the limitations of single inheritance.
Here is how Mixins work in TypeScript:
Example:
class CanRun {
run() {
console.log("Running");
}
}
class CanJump {
jump() {
console.log("Jumping");
}
}
Example:
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
derivedCtor.prototype[name] = baseCtor.prototype[name];
});
});
}
Example:
class SuperHuman implements CanRun, CanJump {
run!: () => void;
jump!: () => void;
}
applyMixins(SuperHuman, [CanRun, CanJump]);
const hero = new SuperHuman();
hero.run(); // Output: Running
hero.jump(); // Output: Jumping
8. How are Classes implemented in TypeScript?
A: Classes in TypeScript are implemented with additional type annotations for properties, methods, and constructors. TypeScript supports object-oriented programming (OOP) principles through encapsulation, inheritance, and polymorphism.
Classes also support access modifiers like public, private, and protected to control properties and methods.
Example: Basic Structure of Class
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): string {
return `Hello, my name is ${this.name}`;
}
}
const person = new Person("Raj", 30);
console.log(person.greet()); // Output: Hello, my name is Raj
9. How do you declare a Namespace in TypeScript?
A: Namespaces allow you to group related code together, helping avoid naming conflicts and organizing code into logical units.
A namespace may contain variables, functions, classes, and interfaces, and it helps encapsulate the code to avoid pollution of the global scope.
Example:
namespace Geometry {
export function calculateArea(radius: number): number {
return Math.PI * radius * radius;
}
export const PI = Math.PI;
}
console.log(Geometry.calculateArea(5)); // Output: 78.53981633974483
10. What are Rest Parameters and how are they used in TypeScript?
A: Rest parameters allow functions to accept an arbitrary number of arguments as an array. In TypeScript, rest parameters are defined using the ... syntax followed by the parameter name, which collects all remaining arguments into an array.
Rest Parameters are useful when you don't know how many arguments will be passed, making your function more flexible and easier to maintain.
Example:
function sum(...numbers: number[]): number {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10
11. How are Objects handled in TypeScript?
A: TypeScript allows objects to be defined as key-value pairs where the keys are typically strings (or symbols), and the values are any data type.
TypeScript adds type safety to objects by allowing you to define specific types for their properties.
Here’s how objects are handled:
1. Defining Objects:
let person: { name: string; age: number } = {
name: "Raj",
age: 30,
};
2. Using Interfaces and Classes:
interface Person {
name: string;
age: number;
}
const user: Person = { name: "Rahul", age: 25 };
class Car {
brand: string;
constructor(brand: string) {
this.brand = brand;
}
}
const myCar = new Car("Tesla");
3. Special Handling: TypeScript supports readonly properties, preventing modifications after initialization.
let user: { readonly name: string } = { name: "Alice" };
// user.name = "Bob"; // ❌ Error: Cannot assign to 'name' because it is a read-only property.
12. What are Type Aliases in TypeScript?
A: A Type Alias allows you to define a custom name for a specific type or combination of types. It’s used for complex types like unions, intersections, or object shapes, making your code more reusable.
Example 1: Defining Type Alias
type Point = { x: number; y: number };
const point: Point = { x: 10, y: 20 };
Example 2: Creating union types using type aliases.
type Status = "success" | "error" | "loading";
13. What are Modules and how do they work in TypeScript?
A: Modules are used to organize and structure code by splitting it into multiple files. By encapsulating code into logical units, you can avoid naming conflicts and improve maintainability. Modules are based on the ES6 module system, which supports import and export.
Here’s how modules work:
Example:
// file: math.ts
export function add(a: number, b: number): number {
return a + b;
}
Example:
// file: app.ts
import { add } from './math';
console.log(add(2, 3)); // Output: 5
Modules can also have a default export for a single value, which simplifies importing:
// file: greet.ts
export default function greet(name: string): string {
return `Hello, ${name}`;
}
// file: app.ts
import greet from './greet';
console.log(greet("Raj")); // Output: Hello, Raj
14. What are Mapped Types in TypeScript?
A: Mapped types allow you to create new types by transforming properties of an existing type. They can be used for creating types that are based on the structure of other types, especially when you need to modify all or some properties.
Here’s how Mapped Types work:
A mapped type is defined using a keyof operator to iterate over keys of a type and apply transformations to the values.
type MyMappedType<T> = {
[K in keyof T]: T[K];
};
Example: Making Properties readonly:
type Person = { name: string; age: number };
type ReadOnlyPerson = { readonly [K in keyof Person]: Person[K] };
const person: ReadOnlyPerson = { name: "Alice", age: 30 };
person.name = "Bob"; // Error: Cannot assign to 'name' because it is a read-only property.
Example: Making Properties optional:
type Person = { name: string; age: number };
type OptionalPerson = { [K in keyof Person]?: Person[K] };
const person: OptionalPerson = { name: "Alice" }; // Valid, age is optional
15. What are Conditional Types in TypeScript?
A: Conditional types allow you to define a type based on a condition that depends on another type. They follow the pattern: T extends U ? X : Y, meaning "if T extends U, use type X, otherwise, use type Y."
Here’s how Conditional Types work:
The type of value is determined by a condition, typically using the extends keyword.
Syntax:
type IsString<T> = T extends string ? "Yes" : "No";
Example 1: Simple Conditional Type
type IsString<T> = T extends string ? "Yes" : "No";
type Result1 = IsString<string>; // "Yes"
type Result2 = IsString<number>; // "No"
Example 2: Conditional Types with Union Types
type ToArray<T> = T extends any[] ? T : T[];
type Result1 = ToArray<number>; // number[]
type Result2 = ToArray<number[]>; // number[]
16. What are Distributive Conditional Types and how do they function?
A: Distributive conditional types are a special form of conditional types that distribute over union types. When the conditional type is applied to a union, it automatically applies the type condition to each member of the union.
Here’s how Distributive Conditional functions:
type IsString<T> = T extends string ? "Yes" : "No";
type Result = IsString<number>; // Result is "No"
type IsString<T> = T extends string ? "Yes" : "No";
type Result = IsString<string | number>; // "Yes" | "No"
Example: Distributive Conditional Type for Union Types
type IsString<T> = T extends string ? "Yes" : "No";
type Result = IsString<string | number>; // "Yes" | "No"
17. How can you support TypeScript files from Node Modules?
A: To use TypeScript files from Node Modules in a TypeScript project, ensure the TypeScript compiler can locate and check the type definitions within those modules.
You can do this by ensuring TypeScript definitions are available either through DefinitelyTyped or package-specific type definitions.
Here are the steps to support TypeScript files from Node Modules:
npm install @types/module-name
{
"compilerOptions": {
"typeRoots": ["node_modules/@types"]
}
}
18. What are the main components of TypeScript?
A: TypeScript consists of components like Compiler and Type System that work together to provide advanced JavaScript features.
Here are the main components:
19. How are Object-Oriented Principles supported by TypeScript?
A: TypeScript supports object-oriented programming (OOP) principles, such as encapsulation, inheritance, and polymorphism, to create more structured and reusable code.
Here’s how they are supported:
Example:
class Car {
private model: string; // Private property, cannot be accessed outside the class
constructor(model: string) {
this.model = model;
}
public getModel(): string {
return this.model; // Public method that can be accessed outside
}
}
const car = new Car("Tesla");
console.log(car.getModel()); // Tesla
// console.log(car.model); // ❌ Error: Property 'model' is private
Example:
class Vehicle {
move() {
console.log("Moving...");
}
}
class Car extends Vehicle {
drive() {
console.log("Driving...");
}
}
const car = new Car();
car.move(); // Inherited method
car.drive(); // Car-specific method
Example:
class Animal {
sound() {
console.log("Some sound");
}
}
class Dog extends Animal {
sound() {
console.log("Bark");
}
}
const animal: Animal = new Dog();
animal.sound(); // Bark
Learn the framework of classes and objects and explore OOP principles. Join the free course on Java Object-oriented Programming.
20. What are the challenges when using Declaration Files in TypeScript?
A: Declaration files (.d.ts files) in TypeScript are used to provide type information for external libraries, especially when the library is written in JavaScript.
Here are the challenges of using Declaration Files:
Intermediate questions will help you understand concepts such as tuples, decorators, and object-oriented programming (OOP) principles like inheritance. Now, let’s explore some advanced TypeScript interview questions.
Advanced interview questions will cover topics like recursion, performance optimization, and design patterns, which are vital for senior developer roles.
Here are some advanced TypeScript interview questions and answers.
1. How do you compile TypeScript using Visual Studio Code?
A: To compile TypeScript code in Visual Studio Code (VS Code), you have to set up the TypeScript compiler (tsc) and configure it within the editor.
Here are the steps to compile:
npm install -g typescript
Run tsc --init in the terminal to generate a default tsconfig.json.
// example.ts
const greet = (name: string): string => {
return `Hello, ${name}!`;
};
console.log(greet("Raj"));
tsc example.ts
In addition, you can set "strict": true in tsconfig.json for strict type-checking options. This is highly recommended for TypeScript projects as it helps catch errors earlier and enforces best practices in your code.
2. What are some of the recent updates in TypeScript?
A: Here are some recent updates in TypeScript that improve developer experience and add new features:
3. How have TypeScript's Awaited Types and Promises improved?
A: TypeScript’s improvements in Awaited types and Promise handling have enhanced working with asynchronous operations and simplify type inference for promises.
Here’s how they have improved:
1. Awaited Type:
The new feature extracts the resolved value from a Promise. It simplifies type declarations by inferring the resolved type of an asynchronous operation.
Example:
type MyPromise = Promise<string>;
type ResolvedType = Awaited<MyPromise>; // string
2. Improved Promise Typing:
Provides better inference when working with asynchronous functions that return Promises. It can automatically infer types inside async functions and Promise chains, reducing the need for explicit type annotations.
Example:
async function fetchData(): Promise<number> {
return 42; // TypeScript infers this as a Promise<number>
}
4. What is Type Assertion in TypeScript? Can you explain its types?
A: Type Assertion tells the compiler to treat a variable as a specific type. It is a way to provide stronger typing when the developer knows more about the value's type than TypeScript can infer.
Here are the different forms of Type Assertion:
Example:
let someValue: any = "Hello World";
let strLength: number = (<string>someValue).length; // Angle-bracket assertion
Example:
let someValue: any = "Hello World";
let strLength: number = (someValue as string).length; // 'as' syntax
5. What are Recursive Type Aliases in TypeScript?
A: Using Recursive Type aliases, you can define types that refer to themselves, enabling the creation of complex structures like recursive data types or nested objects.
They are mainly used in defining self-referential structures like trees, graphs, or linked lists, commonly found in algorithms or data structures.
Working of Recursive Types:
By referring to itself, recursive types allow types to represent nested or hierarchical data, where each item can be of the same type as its parent.
Example:
type NestedObject = {
value: number;
next?: NestedObject; // The type refers to itself
};
const list: NestedObject = {
value: 1,
next: {
value: 2,
next: {
value: 3,
},
},
};
6. How can Generics be implemented in TypeScript?
A: Generics creates reusable and type-safe components, functions, and classes that can operate on multiple types while maintaining the type information.
Using Generics, you can define a function or class without specifying a particular type upfront and instead specify when calling the function/class.
Here’s how it is implemented:
Example:
function identity<T>(arg: T): T {
return arg;
}
const result = identity(5); // result has type 'number'
const stringResult = identity("Hello"); // stringResult has type 'string'
Example:
class Box<T> {
private value: T;
constructor(value: T) {
this.value = value;
}
getValue(): T {
return this.value;
}
}
const numberBox = new Box<number>(123); // Works with numbers
const stringBox = new Box<string>("hello"); // Works with strings
Example:
interface Pair<T, U> {
first: T;
second: U;
}
const pair: Pair<number, string> = { first: 1, second: "one" };
7. What is the difference between the "any" and "unknown" types in TypeScript?
A: Both any and unknown allow variables to hold any type of value, but they differ in the way they handle type safety and usage.
Here’s the difference between any and unknown types:
any | unknown |
No type safety. You can perform any operation. | Type safety is enforced. Operations need type checks before use. |
Use when you don't know the type or want to disable type checking. | Use when you want to handle a type dynamically but still enforce checks for safety. |
Can be assigned to any type without restrictions. | Need type checks before performing operations. |
Ex: let value: any = 42; value = "Hello"; | Ex: let value: unknown = 42; if (typeof value === "string") { console.log(value.toUpperCase()); } |
8. How is Enum used in TypeScript?
A: An Enum defines a set of named constants. Enums can represent discrete values, such as status codes or error types, in a clear and manageable way.
Here’s how it is used:
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right // 3
}
const move: Direction = Direction.Up;
console.log(move); // Output: 0
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}
const favoriteColor: Color = Color.Green;
console.log(favoriteColor); // Output: GREEN
enum Status {
Success = 1,
Failed = "FAILED"
}
9. What are the different ways to define functions in TypeScript?
A: Functions in TypeScript can be defined using traditional function declarations, function expressions, and arrow functions.
Here are the different ways to define functions:
Example:
function greet(name: string): string {
return `Hello, ${name}`;
}
console.log(greet("Raj")); // Output: Hello, Raj
Example:
const sum = function(a: number, b: number): number {
return a + b;
};
console.log(sum(2, 3)); // Output: 5
Example:
const multiply = (a: number, b: number): number => a * b;
console.log(multiply(3, 4)); // Output: 12
Example:
type AddFunction = (a: number, b: number) => number;
const add: AddFunction = (a, b) => a + b;
console.log(add(5, 6)); // Output: 11
10. How does TypeScript handle null and undefined differently compared to JavaScript?
A: In JavaScript, both null and undefined are falsy values. TypeScript enhances handling of these values by providing explicit type checking.
Here’s how null and undefined are handled:
let name: string | null = null;
let count: number | undefined = undefined;
To handle null and undefined safely, you must use union types or enable optional chaining and nullish coalescing operators.
let user = { name: null };
console.log(user.name?.length); // Safely returns 'undefined' without errors
Now that you’ve explored advanced topics like recursion and design optimization in TypeScript, let’s check out the effective strategies to succeed in interviews.
Knowledge of core concepts, such as custom types, and the ability to handle real-world scenarios, like error handling, can help tackle TypeScript interview questions.
Here are some strategies to succeed in TypeScript interview questions.
1. Understand Core TypeScript Concepts
Develop knowledge of using primitive types, custom types, interfaces, generics, and utility types like Partial<> and Readonly<>.
Example: If you're asked to design a user profile interface, instead of relying on plain objects, use an interface:
interface UserProfile {
name: string;
email: string;
age?: number; // Optional property
}
2. Apply in Real-World Scenarios
Learn how to refactor JavaScript code or optimize an existing project using TypeScript. A common scenario involves working with RESTAPIs, where type safety ensures predictable responses.
Example: Instead of dealing with untyped API responses, define a response type to improve reliability:
async function fetchUserData(): Promise<UserProfile> {
const response = await fetch('/api/user');
return response.json();
}
3. Write Type-Safe Code
Writing a clean, type-safe code is essential. TypeScript's strict mode discourages the use of any, so interviewers can expect you to define proper types.
Example: Implement a function to filter active users from a list:
type User = { id: number; name: string; isActive: boolean };
function getActiveUsers(users: User[]): User[] {
return users.filter(user => user.isActive);
}
4. Debugging and Error Handling
Learn how to handle unexpected issues dynamically. A common interview scenario is handling API failures gracefully while maintaining type safety.
Example: A function that fetches user data but might return an error message instead:
type APIResponse<T> = { data?: T; error?: string };
async function fetchUser(): Promise<APIResponse<UserProfile>> {
try {
const response = await fetch('/api/user');
if (!response.ok) throw new Error('Failed to fetch user');
return { data: await response.json() };
} catch (error) {
return { error: (error as Error).message };
}
}
Also Read: What is Debugging in Coding: Tools & Techniques for Debugging Explained
5. Using TypeScript in Large-scale Applications
Knowledge of modularization, type inference, and dependency management becomes crucial when working with microservices or component-driven architectures.
Example: Structure types properly when managing multiple feature modules in a React project:
// types/User.ts
export interface User {
id: number;
name: string;
email: string;
}
// features/UserComponent.tsx
import { User } from '../types/User';
const UserComponent: React.FC<{ user: User }> = ({ user }) => {
return <div>{user.name}</div>;
};
Now that you’ve examined tips to handle TypeScript interview questions, let’s check out ways to boost your knowledge in this field.
Knowledge of TypeScript concepts like mapping, conditional types, and handling unknown variables is essential for cracking interviews for roles such as full-stack developers.
upGrad’s courses in basic web scripting provide foundational knowledge that prepares you for more advanced concepts in web programming.
Here are some courses for upskilling:
Unsure which course aligns with your career goals? upGrad offers personalized counseling to help map your learning journey and choose the right path. You can also visit your nearest upGrad offline center for an interactive experience!
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources