TypeScript Interview Questions
Placement-ready Courses: Enroll Now, Thank us Later!
In a TypeScript interview, you may encounter questions that range from basic syntax to more complex concepts like type inference, advanced types, and asynchronous programming. The interviewer may also ask about your experience with TypeScript tooling and how you approach debugging and testing TypeScript code. Check these TypeScripts Interview Questions to learn more.
TypeScripts Interview Questions
1. What is the output of the following code?
let x = 1; let y = '2'; let z = x + y; console.log(z);
Answer – 12
2. What is the output of the following code?
function add(x: number, y: number): number {
return x + y;
}
let result = add(2, '3');
console.log(result);
Answer – Type Error
3. What is the output of the following code?
class Person {
constructor(private name: string) {}
getName() {
return this.name;
}
}
const person = new Person('John');
console.log(person.getName());
console.log(person.name);
Answer – Property ‘name’ is private and only accessible within class ‘Person’.
4. What is the output of the following code?
let a = [1, 2, 3]; let b = a.map((x) => x * 2); console.log(b);
Answer – [2,4,6]
5. What is the output of the following code?
const person = {
name: 'John',
age: 30,
};
const { name, ...rest } = person;
console.log(name);
console.log(rest);
Answer – Cannot redeclare block-scoped variable ‘name’.
6. What is the output of the following code?
type Car = {
brand: string;
model: string;
};
type Truck = {
brand: string;
model: string;
payload: number;
};
function printVehicle(vehicle: Car | Truck) {
console.log(vehicle.brand + ' ' + vehicle.model);
}
const car: Car = { brand: 'Honda', model: 'Civic' };
const truck: Truck = { brand: 'Ford', model: 'F-150', payload: 1000 };
printVehicle(car);
printVehicle(truck);
Answer –
Honda Civic
Ford F-150
7. What is the output of the following code?
const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter((x) => x % 2 === 0); const doubledNumbers = evenNumbers.map((x) => x * 2); console.log(doubledNumbers);
Answer – [ 4, 8 ]
8. What is the output of the following code?
function greet(name?: string) {
console.log('Hello, ' + name ?? 'world!');
}
greet();
greet('John');
Answer –
Hello, undefined
Hello, John
9. What is the output of the following code?
class Animal {
move(distanceInMeters: number = 0) {
console.log(`Animal moved ${distanceInMeters}m.`);
}
}
class Dog extends Animal {
bark() {
console.log('Woof! Woof!');
}
}
const dog = new Dog();
dog.bark();
dog.move(10);
Answer –
Woof! Woof!
Animal moved 10m.
10. What is the output of the following code?
type Point = [number, number];
function addPoints(a: Point, b: Point): Point {
return [a[0] + b[0], a[1] + b[1]];
}
const point1: Point = [1, 2];
const point2: Point = [3, 4];
const sum = addPoints(point1, point2);
console.log(sum);
Answer – [ 4, 6 ]
11. How would you implement a generic function that reverses the order of an array in TypeScript?
Answer –
function reverse<T>(array: T[]): T[] {
return array.reverse();
}
const numbers = [1, 2, 3];
const reversedNumbers = reverse(numbers);
12. What is a conditional type in TypeScript? Provide an example.
Answer – A conditional type allows you to write a type that depends on a condition. Here’s an example:
type IsString<T> = T extends string ? true : false; const result1: IsString<string> = true; const result2: IsString<number> = false;
13. How would you declare a type that represents an object with a fixed set of properties and their respective types in TypeScript?
Answer – You can use an interface to declare a type that represents an object with a fixed set of properties and their respective types. Here’s an example:
interface Person {
name: string;
age: number;
}
const person: Person = { name: 'John', age: 30 };
14. How would you implement a function that takes a callback as a parameter in TypeScript?
Answer –
function runWithCallback(callback: () => void) {
callback();
}
runWithCallback(() => console.log('Hello, world!'));
15. What is the difference between the private, public, and protected access modifiers in TypeScript?
Answer- private members can only be accessed within the class they are defined in, public members can be accessed from anywhere, and protected members can be accessed within the class they are defined in and any subclasses that extend that class.
16. How would you declare a type that represents an object with dynamic keys in TypeScript?
Answer –
interface DynamicObject {
[key: string]: number;
}
const object: DynamicObject = { a: 1, b: 2, c: 3 };
17. How would you implement a function that takes an array of values and a predicate function and returns an array of values that pass the predicate in TypeScript?
Answer –
function filter<T>(array: T[], predicate: (value: T) => boolean): T[] {
return array.filter(predicate);
}
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = filter(numbers, (value) => value % 2 === 0);
18. How would you create a function that accepts a variable number of arguments with different types in TypeScript?
Answer –
function concatenate(...args: (string | number)[]) {
return args.join('');
}
const result = concatenate('hello', 123, 'world');
19. How would you create a class in TypeScript that implements multiple interfaces?
Answer –
interface Foo {
foo(): void;
}
interface Bar {
bar(): void;
}
class MyClass implements Foo, Bar {
foo() {
console.log('foo');
}
bar() {
console.log('bar');
}
}
20. How would you declare a type that represents a function that returns a Promise in TypeScript?
Answer –
type AsyncFunction<T> = () => Promise<T>;
const fetchData: AsyncFunction<string> = async () => {
const response = await fetch('https://example.com/data');
return response.text();
};
21. How would you declare a type that represents a function with optional parameters in TypeScript?
Answer –
type MyFunction = (a: number, b?: number) => void;
const fn: MyFunction = (a, b) => {
console.log(a, b);
};
fn(1);
fn(1, 2);
22. How would you create a type representing a tuple with a fixed number of elements in TypeScript?
Answer –
type MyTuple = [string, number]; const tuple: MyTuple = ['hello', 123];
23. How would you create a type that represents an object with required and optional properties in TypeScript?
Answer –
type MyObject = {
requiredProp: string;
optionalProp?: number;
};
type MyRequiredObject = Required<MyObject>;
const obj: MyRequiredObject = {
requiredProp: 'hello',
optionalProp: 123,
};
24. What is a discriminated union in TypeScript?
Answer- A discriminated union is a type that combines several types that have a common, discriminative property. Discriminated unions are commonly used with switch statements and type guards.
25. What is a conditional type in TypeScript?
Answer- A conditional type is a type that depends on a condition. Conditional types are commonly used with type inference and type mapping.
26. What is a module in TypeScript?
Answer- A module is a way to organize code and encapsulate functionality. Modules can be exported and imported in other modules using the export and import keywords.
27. What is a type predicate in TypeScript?
Answer- A type predicate is a function that returns a boolean and is used to narrow the value type. Type predicates are commonly used with conditional types and type guards.
28. What is a type predicate in TypeScript?
Answer- A type predicate is a function that returns a boolean and is used to narrow the value type. Type predicates are commonly used with conditional types and type guards.
29. What is the difference between a class and an interface in TypeScript?
Answer- A class is a blueprint for creating objects with properties and methods, while an interface is a contract that describes the shape of an object. You can implement an interface in a class, but you cannot implement a class in an interface.
30. What is the output of the following?
console.log('a');
setTimeout(function () {
console.log('b');
}, 0);
console.log('c');Answer – The output will be “a”, “c”, “b”.
31. Create a class in TypeScript that represents a car. The car should have a make, model, and year property, as well as a method to start the engine.
class Car {
make: string;
model: string;
year: number;
constructor(make: string, model: string, year: number) {
this.make = make;
this.model = model;
this.year = year;
}
startEngine() {
console.log(`Starting ${this.make} ${this.model}...`);
}
}
const myCar = new Car('Toyota', 'Camry', 2022);
myCar.startEngine(); // Output: Starting Toyota Camry...32. Create a class in TypeScript that represents a person. The person should have a name, age, and email property, as well as a method to introduce themselves.
class Person {
name: string;
age: number;
email: string;
constructor(name: string, age: number, email: string) {
this.name = name;
this.age = age;
this.email = email;
}
introduce() {
console.log(
`Hi, my name is ${this.name}, and I am ${this.age} years old. You can reach me at ${this.email}.`
);
}
}
const john = new Person('John Doe', 25, '[email protected]');
john.introduce(); // Output: Hi, my name is John Doe, and I am 25 years old. You can reach me at [email protected].
33. Create a class in TypeScript that represents a bank account. The account should have a balance property and methods to deposit and withdraw money.
class BankAccount {
balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
deposit(amount: number) {
this.balance += amount;
}
withdraw(amount: number) {
if (amount > this.balance) {
console.log('Insufficient funds');
return;
}
this.balance -= amount;
}
}
const myAccount = new BankAccount(1000);
myAccount.deposit(500);
myAccount.withdraw(200);
console.log(myAccount.balance); // Output: 1300
34. Create a class in TypeScript that represents a calculator. The calculator should have methods to add, subtract, multiply, and divide numbers.
class Calculator {
add(a: number, b: number) {
return a + b;
}
subtract(a: number, b: number) {
return a - b;
}
multiply(a: number, b: number) {
return a * b;
}
divide(a: number, b: number) {
if (b === 0) {
console.log('Cannot divide by zero');
return;
}
return a / b;
}
}
const myCalculator = new Calculator();
console.log(myCalculator.add(2, 3)); // Output: 5
console.log(myCalculator.subtract(5, 2)); // Output: 3
console.log(myCalculator.multiply(4, 6)); // Output: 24
console.log(myCalculator.divide(10, 2)); // Output: 5
35. Create a class in TypeScript that represents a book. The book should have a title, author, and number of pages property, as well as a method to display its information.
class Book {
title: string;
author: string;
pages: number;
constructor(title: string, author: string, pages: number) {
this.title = title;
this.author = author;
this.pages = pages;
}
displayInfo() {
console.log(
`Title: ${this.title}\nAuthor: ${this.author}\nNumber of pages: ${this.pages}`
);
}
}
const myBook = new Book('The Great Gatsby', 'F. Scott Fitzgerald', 180);
myBook.displayInfo(); // Output: Title: The Great Gatsby Author: F. Scott Fitzgerald Number of pages: 180
36. Create a class in TypeScript that represents a circle. The circle should have a radius property and methods to calculate its area and circumference.
class Circle {
radius: number;
constructor(radius: number) {
this.radius = radius;
}
getArea() {
return Math.PI * this.radius ** 2;
}
getCircumference() {
return 2 * Math.PI * this.radius;
}
}
const myCircle = new Circle(5);
console.log(myCircle.getArea()); // Output: 78.53981633974483
console.log(myCircle.getCircumference()); // Output: 31.4159265358979337. Create a class in TypeScript that represents a student. The student should have a name, age, and an array of courses they are taking, as well as a method to display their information.
class Student {
name: string;
age: number;
courses: string[];
constructor(name: string, age: number, courses: string[]) {
this.name = name;
this.age = age;
this.courses = courses;
}
displayInfo() {
console.log(
`Name: ${this.name}\nAge: ${this.age}\nCourses: ${this.courses.join(
', '
)}`
);
}
}
const myStudent = new Student('Jane Smith', 20, [
'Calculus',
'Physics',
'Computer Science',
]);
myStudent.displayInfo(); // Output: Name: Jane Smith Age: 20 Courses: Calculus, Physics, Computer Science
38. Create a class in TypeScript that represents a point in two-dimensional space. The point should have x and y properties and methods to calculate its distance from another point.
class Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
distanceFrom(point: Point) {
return Math.sqrt((this.x - point.x) ** 2 + (this.y - point.y) ** 2);
}
}
const pointA = new Point(0, 0);
const pointB = new Point(3, 4);
console.log(pointA.distanceFrom(pointB)); // Output: 5
39. Create a class in TypeScript that represents a shape. The shape should have a name and methods to calculate its area and perimeter.
class Shape {
name: string;
constructor(name: string) {
this.name = name;
}
getArea() {}
getPerimeter() {}
}
class Rectangle extends Shape {
width: number;
height: number;
constructor(name: string, width: number, height: number) {
super(name);
this.width = width;
this.height = height;
}
getArea() {
return this.width * this.height;
}
getPerimeter() {
return 2 * (this.width + this.height);
}
}
const myRectangle = new Rectangle('My Rectangle', 5, 10);
console.log(myRectangle.getArea()); // Output: 50
console.log(myRectangle.getPerimeter()); //
40. Create a class in TypeScript that represents a bank account. The account should have a balance property and methods to deposit and withdraw money.
class BankAccount {
balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
deposit(amount: number) {
this.balance += amount;
}
withdraw(amount: number) {
if (this.balance >= amount) {
this.balance -= amount;
} else {
console.log('Insufficient funds.');
}
}
}
const myAccount = new BankAccount(100);
console.log(myAccount.balance); // Output: 100
myAccount.deposit(50);
console.log(myAccount.balance); // Output: 150
myAccount.withdraw(75);
console.log(myAccount.balance); // Output: 75
myAccount.withdraw(100); // Output: Insufficient funds.41. Create a function called reverseArray that takes an array of any type and returns a new array with the elements in reverse order.
function reverseArray<T>(arr: T[]): T[] {
return arr.reverse();
}
console.log(reverseArray([1, 2, 3, 4])); // Output: [4, 3, 2, 1]
console.log(reverseArray(['a', 'b', 'c'])); // Output: ["c", "b", "a"]42. Create a function called combineArrays that takes two arrays of the same type and returns a new array with the elements of both arrays concatenated.
function combineArrays<T>(arr1: T[], arr2: T[]): T[] {
return arr1.concat(arr2);
}
console.log(combineArrays([1, 2, 3], [4, 5, 6])); // Output: [1, 2, 3, 4, 5, 6]
console.log(combineArrays(['a', 'b', 'c'], ['d', 'e', 'f'])); // Output: ["a", "b", "c", "d", "e", "f"]
43. Create a function called mapArray that takes an array of any type and a function that maps each element of the array to a new value. The function should return a new array with the mapped values.
function mapArray<T, U>(arr: T[], mapper: (item: T) => U): U[] {
return arr.map(mapper);
}
console.log(mapArray([1, 2, 3], (x) => x * 2)); // Output: [2, 4, 6]
console.log(mapArray(['a', 'b', 'c'], (x) => x.toUpperCase())); // Output: ["A", "B", "C"]
44. Create a class called Stack that uses generics to implement a stack data structure. The class should have methods push and pop to add and remove elements from the stack, as well as a property size that returns the number of elements in the stack.
class Stack<T> {
private elements: T[] = [];
push(element: T) {
this.elements.push(element);
}
pop(): T | undefined {
return this.elements.pop();
}
get size(): number {
return this.elements.length;
}
}
const myStack = new Stack<number>();
myStack.push(1);
myStack.push(2);
myStack.push(3);
console.log(myStack.pop()); // Output: 3
console.log(myStack.size); // Output: 2
45. Create a function called getObjectProperty that takes an object of type T and a string property name, and returns the value of that property. The function should use a generic type parameter to ensure that the property name is valid for the object type.
function getObjectProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const myObj = { name: 'Jane', age: 30 };
console.log(getObjectProperty(myObj, 'name')); // Output: "Jane"
console.log(getObjectProperty(myObj, 'age')); // Output: 30
46. Create a module called math that exports a function called add that takes two numbers and returns their sum.
export function add(a: number, b: number): number {
return a + b;
}
In another file, you can import the add function and use it:
import { add } from './math';
console.log(add(1, 2)); // Output: 3
47. Create a module called utilities that exports a class called Logger that logs messages to the console. The class should have a method called log that takes a string message and logs it to the console.
export class Logger {
log(message: string) {
console.log(message);
}
}
In another file, you can import the Logger class and use it:
import { Logger } from './utilities';
const logger = new Logger();
logger.log('Hello, world!'); // Output: "Hello, world!"
48. Create a module called models that exports an interface called User that describes a user object with name and age properties.
export interface User {
name: string;
age: number;
}
In another file, you can import the User interface and use it:
import { User } from './models';
const user: User = { name: 'Jane', age: 30 };
console.log(user.name); // Output: "Jane"
49. Create a module called api that exports a function called fetchData that retrieves data from a remote server. The function should take a URL string and return a Promise that resolves to the response data.
export function fetchData(url: string): Promise<any> {
return fetch(url).then((response) => response.json());
}
In another file, you can import the fetchData function and use it:
import { fetchData } from './api';
fetchData('https://example.com/data.json').then((data) => {
console.log(data);
});
50. Create a module called config that exports a constant called API_KEY that contains a secret API key. The module should also export a function called getApiKey that returns the value of API_KEY.
const API_KEY = 'secret_key';
export function getApiKey(): string {
return API_KEY;
}
In another file, you can import the getApiKey function and use it:
import { getApiKey } from './config';
console.log(getApiKey()); // Output: "secret_key"
51. Write a function getLength that takes a string or an array and returns the length of the string or the array.
function getLength(input: string | any[]): number {
return input.length;
}
console.log(getLength('hello')); // Output: 5
console.log(getLength([1, 2, 3])); // Output: 3
52. Define a type Person that has two properties name and age, where name is a string and age is a number. Then define a type Employee that has three properties name, age, and jobTitle, where jobTitle is a string. Create a union type PersonOrEmployee that can be either a Person or an Employee.
type Person = {
name: string;
age: number;
};
type Employee = {
name: string;
age: number;
jobTitle: string;
};
type PersonOrEmployee = Person | Employee;
53. Write a function square that takes a number or a string that represents a number and returns the square of the number. If a string is passed, the function should parse it to a number first.
function square(input: number | string): number {
const num = typeof input === 'string' ? parseFloat(input) : input;
return num * num;
}
console.log(square(5)); // Output: 25
console.log(square('7')); // Output: 49
54. Define a type Shape that can be either a Circle or a Rectangle. A Circle has a property radius that is a number, and a Rectangle has properties width and height that are numbers. Create a union type CircleOrRectangle that can be either a Circle or a Rectangle.
type Circle = {
kind: 'circle';
radius: number;
};
type Rectangle = {
kind: 'rectangle';
width: number;
height: number;
};
type Shape = Circle | Rectangle;
55. Write a function join that takes two strings or two arrays and concatenates them. If both arguments are strings, the function should return a concatenated string. If both arguments are arrays, the function should return a new array that contains the elements of both arrays. And If one argument is a string and the other is an array, the function should throw an error.
function join(a: string | any[], b: string | any[]): string | any[] {
if (typeof a === 'string' && typeof b === 'string') {
return a + b;
} else if (Array.isArray(a) && Array.isArray(b)) {
return [...a, ...b];
} else {
throw new Error('Arguments must be either both strings or both arrays');
}
}
console.log(join('hello', 'world')); // Output: "helloworld"
console.log(join([1, 2], [3, 4])); // Output: [1, 2, 3, 4]
join('hello', [1, 2]); // Throws an error
56. Write a function sum that takes an array of numbers and returns the sum of all the numbers.
function sum(numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum([1, 2, 3]));
console.log(sum([4, 5, 6]));
57. Define a type Person that has two properties name and age, where name is a string and age is a number. Create an array people that contains three objects of type Person.
type Person = {
name: string;
age: number;
};
const people: Person[] = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 },
];
58. Write a function first that takes an array and returns the first element of the array. If the array is empty, the function should return undefined.
function first<T>(array: T[]): T | undefined {
return array.length > 0 ? array[0] : undefined;
}
console.log(first([1, 2, 3])); // Output: 1
console.log(first([])); // Output: undefined
59. Define a type Animal that has two properties name and species, where both are strings. Create an array animals that contains two objects of type Animal, where one animal is named “Tom” and the other is named “Jerry”.
type Animal = {
name: string;
species: string;
};
const animals: Animal[] = [
{ name: 'Tom', species: 'Cat' },
{ name: 'Jerry', species: 'Mouse' },
];
60. Write a function contains that takes an array and an element, and returns true if the array contains the element, and false otherwise.
function contains<T>(array: T[], element: T): boolean {
return array.includes(element);
}
console.log(contains([1, 2, 3], 2)); // Output: true
console.log(contains([4, 5, 6], 1)); // Output: false
Conclusion
In conclusion, TypeScript has become an essential tool for web developers who want to build complex and scalable applications. Its static type checking, advanced features, and compatibility with popular frontend frameworks make it a valuable skill to have in the current job market. Therefore, preparing for a TypeScript interview is crucial to demonstrating your knowledge of TypeScript syntax, concepts, and applications.
In addition to mastering TypeScript fundamentals, you may also need to showcase your experience with TypeScript tooling, debugging, and testing, as well as your understanding of how TypeScript integrates with popular frameworks like Angular and React. By investing time in studying and practicing TypeScript, you can position yourself as a skilled TypeScript developer who can deliver high-quality, scalable, and maintainable applications.
Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

