TypeScript Interview Questions
Master the most commonly asked interview questions with comprehensive, expert-crafted answers designed to help you succeed.
What are the advantages of using TypeScript?
TypeScript offers several advantages over plain JavaScript, making it a preferred choice for developing large-scale applications. Some of the key benefits include:
- Cross-Browser Compatibility: TypeScript compiles to standard JavaScript, which can run on all modern browsers and JavaScript engines without modification.
- Static Typing: TypeScript allows developers to define variable types explicitly. This helps catch type-related errors at compile time rather than at runtime, leading to more reliable code.
- Enhanced Developer Productivity: With features like IntelliSense, auto-completion, and type inference, TypeScript improves the overall developer experience and productivity in modern IDEs.
- Support for Modern JavaScript Features: TypeScript supports ECMAScript features such as async/await, decorators, and arrow functions even before they are fully adopted in browsers.
- Namespace and Module Support: TypeScript provides organizational tools such as namespaces and modules to better structure and encapsulate code.
- Early Error Detection: Unlike JavaScript, TypeScript reports errors during the compilation phase, allowing developers to fix issues early in the development cycle.
Overall, TypeScript enhances code quality, maintainability, and scalability—especially beneficial in enterprise-level and long-term projects.
Explain the data types available in TypeScript.
TypeScript supports a variety of data types that help developers define variables with precise behavior. These data types are mainly categorized into two groups: built-in (or primitive) data types and user-defined data types.
1. Built-in Data Types: These are the standard data types provided by TypeScript and are directly available for use. They include:
- string: Used to represent textual data, such as
"Hello"
or"TypeScript"
. - number: Represents numeric values, including integers and floating-point numbers like
10
or3.14
. - boolean: Stores logical values — either
true
orfalse
. - null: Represents an explicitly assigned empty value to a variable.
- undefined: Indicates that a variable has been declared but not assigned any value.
- any: Allows a variable to hold a value of any type, bypassing type checking.
- void: Commonly used with functions to specify that they do not return any value.
2. User-defined Data Types: These are custom types created by developers to handle more complex data structures. They include:
- arrays: Used to store collections of values of any data type, such as
let scores: number[] = [85, 90, 95]
. - enums: A way to define named constants, improving code readability. Example:
enum Direction { Up, Down, Left, Right }
. - classes: Define blueprints for creating objects with properties and methods, allowing encapsulation of related data.
- interfaces: Specify the structure that objects must follow, serving as contracts in the code for consistency and reusability.
Understanding these data types allows developers to write more structured, type-safe, and maintainable code in TypeScript.
In how many ways can we declare variables in TypeScript?
In TypeScript, there are three main ways to declare variables: using var
, let
, and const
. Each has distinct behaviors regarding scope, hoisting, and mutability.
The var
keyword is the traditional way to declare variables. It is function-scoped, meaning it is accessible throughout the function in which it's declared, regardless of block boundaries. However, it can lead to unexpected behavior due to hoisting and is generally avoided in modern TypeScript code.
The let
keyword provides block-level scoping, which limits the variable's accessibility to the block it is declared in. It allows reassignment but prevents redeclaration within the same scope, making it a safer choice than var
for most use cases.
The const
keyword is also block-scoped and is used to declare variables that should not be reassigned after their initial assignment. Although the reference itself cannot change, if the value is an object or array, its internal structure can still be modified.
By understanding the differences between these declaration methods, developers can write more predictable and maintainable TypeScript code.
How to declare a function with typed annotation in TypeScript?
function annotatedFunc(myName: string, age: number): string {
return `My name is ${myName} and my age is ${age}.`;
}
console.log(annotatedFunc("Emrit", 22));
// Output: My name is Emrit and my age is 22
// This will throw a compile-time error:
console.log(annotatedFunc("Neha", "18"));
// Error: Argument of type '"18"' is not assignable to parameter of type 'number'.
Describe the 'any' type in TypeScript.
any
type in TypeScript is used when you want to disable type checking for a particular variable. It allows you to assign a value of any type to a variable, making it useful in situations where you don't know the exact shape or structure of the data — such as dynamic user input, third-party libraries, or API responses. By using any
, you are telling TypeScript to trust you and not perform strict type checks on that variable.
Here's a practical example that demonstrates how any
is commonly used when working with JSON data:
let studentData: string = `{
"studentName": "Aakash",
"studentID": 12345,
"studentCourse": "B. Tech"
}`;
let student: any = JSON.parse(studentData);
console.log(student.studentName, student.studentID, student.studentCourse);
// Output: Aakash 12345 B. Tech
student
is typed as any
to allow access to properties without any compile-time errors, even though TypeScript does not know the structure of the parsed object. However, overusing any
can lead to bugs, so it should be used only when necessary.
Can we specify the optional properties to TypeScript Object, if Yes, explain How?
?
) right after the property name. Optional properties are not required during object creation but can be added later if needed. This makes object definitions more flexible and avoids unnecessary strictness in situations like API responses, configuration objects, or dynamic user inputs.
Here’s a simple example that shows how to use optional properties in TypeScript:
const myObj: { name: string; desc: string; est?: number } = {
name: "SmartTech",
desc: "An Innovation Hub",
};
console.log(myObj);
// Output: { name: 'SmartTech', desc: 'An Innovation Hub' }
myObj.est = 2020;
console.log(myObj);
// Output: { name: 'SmartTech', desc: 'An Innovation Hub', est: 2020 }
?
after the property name (like est?
), you're telling TypeScript that this field is optional and doesn't need to be initialized when the object is first created.
Differentiate between the .ts and .tsx file extensions given to the TypeScript file.
.ts
extension is used for writing standard TypeScript code that does not include any JSX. These files typically consist of logic such as classes, utility functions, reducers, services, or any TypeScript-specific functionality that operates independently of the UI. Since JSX syntax is not supported inside .ts
files, they're ideal for non-UI logic and backend-like structures in TypeScript projects.
In contrast, the .tsx
extension is used when the file includes JSX, which is common in React applications. JSX allows embedding HTML-like syntax within JavaScript or TypeScript, and .tsx
enables TypeScript to correctly parse and compile such code. These files are typically used for creating React components that return JSX as their UI output. In summary, .ts
is meant for non-JSX logic, whereas .tsx
is essential when integrating TypeScript with JSX in a React-based project.
Name the access modifiers supported in TypeScript
TypeScript supports the following access modifiers to control the visibility of class members:
- Public: Members declared as public can be accessed from anywhere, including within the class, derived classes, and from instances.
- Private: Members declared as private can only be accessed within the class in which they are defined.
- Protected: Members declared as protected can be accessed within the class and by derived classes, but not from class instances.
Explain Loops in TypeScript
Loops in TypeScript allow the execution of a statement or block of statements repeatedly until a certain condition is met. Common loop types include:
- For Loop: Executes a block of code a specific number of times. Best used when the number of iterations is known.
- While Loop: Repeats a block of code as long as the given condition evaluates to true. The condition is checked before each iteration.
- Do...While Loop: Similar to the while loop, but the condition is checked after each iteration, ensuring the loop executes at least once.
What is the use of the tsconfig.json file?
The tsconfig.json
file is a configuration file in JSON format used to define how the TypeScript compiler should compile the project. The presence of this file indicates the root of a TypeScript project. It includes settings such as:
compilerOptions
: Specifies compiler settings like target ECMAScript version, module system, and type checking rules.include
andexclude
: Defines which files or directories should be included or excluded from compilation.- Path mappings and project references.
What are import and export keywords in TypeScript?
In TypeScript, the export
keyword is used to make variables, functions, classes, or type aliases accessible outside the current file. The import
keyword is used to bring in exported members from another module.
Example:
// greetings.ts
export function greet(name: string) {
return `Hello, ${name}`;
}
// app.ts
import { greet } from './greetings';
TypeScript supports both named exports and default exports for flexible module structuring.
Can TypeScript be used for the backend?
Yes, TypeScript can be used for backend development, commonly in combination with Node.js. This setup provides the benefits of strong typing, better IntelliSense, and improved maintainability.
Popular frameworks such as NestJS and Express (with TypeScript) allow developers to build scalable and robust server-side applications.
How will you check if a variable is null or undefined in TypeScript?
You can check for null or undefined values explicitly:
if (value !== null && value !== undefined) {
// Safe to use value
}
Alternatively, a simple truthy check works for most cases:
if (value) {
// Executes if value is truthy
}
The explicit check is preferred when distinguishing between falsey values like 0 or empty strings.
What is an Interface with reference to TypeScript?
An interface in TypeScript defines the structure that a class or object must follow, containing only declarations without implementations.
Example:
interface Person {
name: string;
age: number;
}
class Employee implements Person {
constructor(public name: string, public age: number) {}
}
Interfaces ensure type safety by enforcing a contract that implementing classes must follow.
Describe ‘as’ syntax in TypeScript.
The as
keyword in TypeScript is used for type assertions, allowing you to inform the compiler about a variable’s specific type.
Example:
let id: any = "123";
let numericId = id as number;
This is often used when working with DOM elements or external data where the type is known by the developer.
Define Lambda function.
A lambda function (arrow function) is an anonymous function with a concise syntax that also binds this
to the enclosing scope.
Example:
let sum = (a: number, b: number): number => a + b;
console.log(sum(5, 10)); // Output: 15
How to create objects in TypeScript?
Objects in TypeScript can be created with explicit type annotations for properties and their types.
Example:
let point: { x: number; y: number } = {
x: 10,
y: 20
};
Keys must be unique and match the defined types.
Explain Tuples in TypeScript with Example.
A tuple is an ordered collection of elements where each position has a specific type. Tuples are useful for grouping related values of different types.
Example:
let user: [number, string] = [1, "Alice"];
They can also be used as function parameters to pass multiple values of different types together.
Explain the arrow function syntax in TypeScript.
Arrow functions in TypeScript provide a shorter and more convenient way to write functions. They are also referred to as lambdas in other languages.
Example – Regular Function:
function add(x: number, y: number): number {
let sum = x + y;
return sum;
}
Equivalent Arrow Function:
let add = (x: number, y: number): number => {
let sum = x + y;
return sum;
};
Shortened Arrow Function: If the body has only one expression, you can omit the braces and return
keyword:
let add = (x: number, y: number): number => x + y;
Arrow functions are often used as anonymous callbacks:
let numbers = [3, 5, 9, 15, 34, 35];
let fiveMultiples = numbers.filter(num => (num % 5) == 0);
console.log(fiveMultiples); // [5, 15, 35]
How to create objects in TypeScript?
Objects in TypeScript are collections of key-value pairs, where keys are unique. Unlike arrays that use numeric indexes, objects allow keys of different types (usually strings or symbols).
You can define an object type by specifying its property names and types:
let pt: { x: number; y: number } = {
x: 10,
y: 20
};
This explicit type definition ensures that the object contains only the specified properties with the correct types.
Why Choose Our Question Bank?
Get access to expertly crafted answers and comprehensive preparation materials
Complete Collection
Access all 20 carefully curated questions covering every aspect of TypeScript interviews
Expert Answers
Get detailed, professional answers crafted by industry experts with real-world experience
Instant Access
Start preparing immediately with instant access to all questions and answers after sign-up