*** 1. Write a Generic Queue Class in TypeScript
Definition
A Generic Queue allows storing elements of any type while maintaining type safety.
Example
class Queue<T> {
private items: T[] = [];
enqueue(item: T): void {
this.items.push(item);
}
dequeue(): T | undefined {
return this.items.shift();
}
front(): T | undefined {
return this.items[0];
}
isEmpty(): boolean {
return this.items.length === 0;
}
}
const numberQueue = new Queue<number>();
numberQueue.enqueue(10);
numberQueue.enqueue(20);
console.log(numberQueue.dequeue()); // 10
Key Interview Points
-
<T>represents a generic type. - Generics improve reusability and type safety.
- Queue follows FIFO (First In First Out).
Interview Insight
Interviewers often ask generics to test:
- Reusable code design
- Type safety understanding
- OOP concepts
*** 2. Create an Enum and Explain Its Behavior
Definition
Enums allow defining a set of named constants.
Example
enum Direction {
Up,
Down,
Left,
Right
}
let move: Direction = Direction.Up;
console.log(move); // 0
String Enum Example
enum Status {
Success = "SUCCESS",
Failed = "FAILED",
Pending = "PENDING"
}
console.log(Status.Success);
Behavior
- Numeric enums start from
0by default. - String enums store readable string values.
- Enums improve code readability and maintainability.
Key Interview Points
- Numeric enums support reverse mapping.
- String enums are safer for APIs and debugging.
Interview Insight
Enums are commonly asked in:
- Backend APIs
- Status handling
- Role management systems
** 3. Write a Function Using Optional Parameters
Definition
Optional parameters are parameters that may or may not be passed.
Syntax
parameter?: type
Example
function greet(name: string, message?: string): string {
return `${message || "Hello"} ${name}`;
}
console.log(greet("Jitendra"));
console.log(greet("Jitendra", "Welcome"));
Key Interview Points
- Optional parameters use
?. - They must come after required parameters.
Interview Insight
Interviewers may ask:
- Difference between optional and default parameters
- Parameter ordering rules
** 4. Write a Function Using Rest Parameters
Definition
Rest parameters allow passing multiple arguments into a function.
Example
function sum(...numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(10, 20, 30));
Key Interview Points
- Rest parameter uses
.... - Only one rest parameter is allowed.
- It must be the last parameter.
Interview Insight
Frequently asked in:
- Utility function design
- Functional programming concepts
*** 5. Implement Inheritance Using Classes
Definition
Inheritance allows one class to acquire properties and methods from another class.
Example
class Animal {
eat(): void {
console.log("Animal is eating");
}
}
class Dog extends Animal {
bark(): void {
console.log("Dog is barking");
}
}
const dog = new Dog();
dog.eat();
dog.bark();
Key Interview Points
-
extendskeyword is used for inheritance. - Child class inherits parent class members.
Interview Insight
Very commonly asked with:
- Polymorphism
- Method overriding
-
superkeyword
** 6. Create a Typed Arrow Function
Example
const multiply = (a: number, b: number): number => {
return a * b;
};
console.log(multiply(5, 4));
Key Interview Points
- Arrow functions provide shorter syntax.
- Type annotations improve safety.
Interview Insight
Interviewers often ask:
- Difference between normal and arrow functions
-
thisbehavior in arrow functions
* 7. Create a Readonly Property Example
Definition
Readonly properties cannot be modified after initialization.
Example
class Employee {
readonly empId: number;
constructor(empId: number) {
this.empId = empId;
}
}
const emp = new Employee(101);
console.log(emp.empId);
// emp.empId = 200; // Error
Key Interview Points
-
readonlyprevents modification. - Value can only be assigned:
- During declaration
- Inside constructor
Interview Insight
Frequently used in:
- Immutable object design
- Secure data modeling
*** 8. Create an Interface and Implement It in a Class
Definition
Interfaces define the structure of an object or class.
Example
interface Person {
name: string;
age: number;
display(): void;
}
class Student implements Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
display(): void {
console.log(`Name: ${this.name}, Age: ${this.age}`);
}
}
const student = new Student("Jitendra", 25);
student.display();
Key Interview Points
- Interfaces enforce structure.
-
implementskeyword is used in classes.
Interview Insight
Very frequently asked because interfaces are heavily used in:
- Angular
- React props typing
- API response modeling
*** 9. Demonstrate Function Overloading
Definition
Function overloading allows multiple function signatures with one implementation.
Example
function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any {
return a + b;
}
console.log(add(10, 20));
console.log(add("Hello ", "World"));
Key Interview Points
- Multiple signatures
- Single implementation function
- Improves flexibility and type safety
Interview Insight
Interviewers use this question to test:
- Type system knowledge
- Function signature understanding
*** 10. Create a Module Using Export/Import
mathUtils.ts
export function add(a: number, b: number): number {
return a + b;
}
export const PI = 3.14;
app.ts
import { add, PI } from "./mathUtils";
console.log(add(5, 10));
console.log(PI);
Key Interview Points
-
exportexposes members. -
importconsumes exported members. - Modules improve code organization.
Interview Insight
Frequently asked in:
- Node.js projects
- React applications
- Large-scale TypeScript applications
** 11. Demonstrate Type Assertions Using as Syntax
Definition
Type assertions tell TypeScript to treat a value as a specific type.
Example
let value: unknown = "TypeScript";
let strLength: number = (value as string).length;
console.log(strLength);
Alternative Syntax
let value: any = "Hello";
let len = (<string>value).length;
Key Interview Points
-
assyntax is preferred in modern TypeScript. - Type assertions do not change runtime behavior.
- Used when TypeScript cannot infer the correct type.
Interview Insight
Frequently asked with:
- DOM manipulation
- API response handling
-
unknownvsany
*** 12. Create an Example Using Union Types
Definition
Union types allow a variable to store multiple possible types.
Syntax
type1 | type2
Example
function printId(id: number | string): void {
console.log("ID:", id);
}
printId(101);
printId("EMP101");
Key Interview Points
- Union types improve flexibility.
- Type narrowing is often used with unions.
Type Narrowing Example
function display(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}
}
Interview Insight
Very commonly asked in:
- API response handling
- React props typing
- Dynamic input validation
* 13. Demonstrate Destructuring in Function Parameters
Definition
Destructuring extracts values directly from objects or arrays.
Example
function displayUser(
{ name, age }: { name: string; age: number }
): void {
console.log(`Name: ${name}`);
console.log(`Age: ${age}`);
}
displayUser({
name: "Jitendra",
age: 25
});
Key Interview Points
- Improves readability.
- Commonly used in React and API handling.
Interview Insight
Interviewers may ask:
- Object destructuring
- Array destructuring
- Default values with destructuring
*** 14. Create a Generic Identity Function
Definition
A generic identity function returns the same type passed into it.
Example
function identity<T>(value: T): T {
return value;
}
console.log(identity<string>("TypeScript"));
console.log(identity<number>(100));
Key Interview Points
- Generics improve reusability.
- Preserves type information.
Interview Insight
This is one of the most frequently asked generic questions in TypeScript interviews.
* 15. Create an Anonymous Callback Function
Definition
An anonymous callback function is a function passed directly as an argument without a name.
Example
const numbers = [1, 2, 3, 4];
numbers.forEach(function(num) {
console.log(num);
});
Arrow Function Version
numbers.forEach((num) => {
console.log(num);
});
Key Interview Points
- Widely used in asynchronous programming.
- Common in array methods like:
-
map() -
filter() -
forEach()
-
Interview Insight
Interviewers often ask callback-related questions with:
- Promises
- Event handling
- Async programming
** 16. Write Code Using Decorators
Definition
Decorators add metadata or modify class behavior.
Example
function Logger(constructor: Function) {
console.log("Class Created");
}
@Logger
class Employee {
constructor() {
console.log("Employee Object Created");
}
}
const emp = new Employee();
Key Interview Points
- Decorators use
@syntax. - Experimental feature in TypeScript.
- Enabled using:
"experimentalDecorators": true
Interview Insight
Frequently asked in:
- Angular interviews
- Advanced TypeScript discussions
*** 17. Demonstrate Method Overriding
Definition
Method overriding allows a child class to provide a specific implementation of a parent method.
Example
class Animal {
sound(): void {
console.log("Animal makes sound");
}
}
class Dog extends Animal {
sound(): void {
console.log("Dog barks");
}
}
const dog = new Dog();
dog.sound();
Key Interview Points
- Requires inheritance.
- Runtime polymorphism concept.
Interview Insight
Often asked together with:
- OOP principles
- Polymorphism
-
superkeyword
** 18. Write an Example Using Getter/Setter
Definition
Getters and setters control access to class properties.
Example
class Person {
private _name: string = "";
get name(): string {
return this._name;
}
set name(value: string) {
this._name = value;
}
}
const person = new Person();
person.name = "Jitendra";
console.log(person.name);
Key Interview Points
-
getretrieves value. -
setupdates value. - Useful for validation and encapsulation.
Interview Insight
Interviewers often ask:
- Difference between methods and getters/setters
- Encapsulation concepts
* 19. Create a Namespace Example
Definition
Namespaces organize related code logically.
Example
namespace MathUtils {
export function add(a: number, b: number): number {
return a + b;
}
export const PI = 3.14;
}
console.log(MathUtils.add(5, 10));
console.log(MathUtils.PI);
Key Interview Points
-
exportexposes members inside namespace. - Used before ES Modules became common.
Interview Insight
Modern applications usually prefer:
- ES Modules
-
import/export
But interviewers may still ask namespaces for legacy TypeScript understanding.
*** 20. Demonstrate Strict Null Checking
Definition
Strict null checking prevents assigning null or undefined to variables unless explicitly allowed.
Enable in tsconfig.json
{
"compilerOptions": {
"strictNullChecks": true
}
}
Example
let username: string;
// username = null; // Error
let user: string | null = null;
user = "Jitendra";
Optional Null Check Example
function printLength(text?: string) {
console.log(text?.length);
}
Key Interview Points
- Improves type safety.
- Prevents runtime null errors.
-
?optional chaining helps handle null safely.
Interview Insight
Very frequently asked because strict null checking is heavily used in:
- Enterprise applications
- Angular projects
- Backend APIs