Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

TypeScript Interview Questions and Answers

Prepare for TypeScript interviews with commonly asked conceptual questions, practical coding problems, OOP concepts, type system questions, and asynchronous programming examples.

1. How to Prepare for a TypeScript Interview

TypeScript interviews commonly cover JavaScript fundamentals, TypeScript's type system, interfaces, functions, classes, modules, asynchronous programming, and practical problem-solving.

📘
Fundamentals

Types, variables, inference, and interfaces.

🏗️
OOP

Classes, inheritance, encapsulation, and generics.

⚡
Async Programming

Promises, async/await, and error handling.

💻
Coding Practice

Arrays, functions, objects, and problem-solving.

2. Basic TypeScript Interview Questions

Q1

What is TypeScript?

TypeScript is a programming language built on JavaScript that adds static type checking and other development features. TypeScript code is typically compiled or transformed into JavaScript for execution.
Q2

What is the difference between JavaScript and TypeScript?

JavaScript TypeScript
Does not provide TypeScript's static type system. Adds static type checking.
Can run directly in browsers. Usually needs to be compiled or transformed to JavaScript.
Types are determined dynamically at runtime. Types are checked during development and compilation.
Supports functions, classes, and objects. Supports these JavaScript features plus TypeScript-specific types.
Q3

What are the benefits of TypeScript?

TypeScript provides static type checking, improved editor support, better refactoring, clearer function contracts, and stronger maintainability for large codebases.
Q4

What is type inference?

Type inference means TypeScript determines a type from the available information without requiring an explicit annotation in every case.

let courseName = "TypeScript";
let duration = 3;

console.log(courseName);
console.log(duration);
TypeScript infers string for courseName and number for duration.
Q5

What is the difference between let, const, and var?

Keyword Scope Can Reassign?
var Function-scoped Yes
let Block-scoped Yes
const Block-scoped No reassignment
Note that a const object or array can still have its contents modified. The variable binding itself cannot be reassigned.
Q6

What are basic types in TypeScript?

Common types include string, number, boolean, arrays, tuples, object types, literal types, union types, unknown, void, and never.
let name: string = "Rahul";
let age: number = 25;
let isActive: boolean = true;
let marks: number[] = [80, 90, 75];
Q7

What is the difference between any and unknown?

any disables most type checking for the value. unknown can hold any value, but generally requires type narrowing before the value can be used in a type-specific way. Prefer unknown when the value's type is not known.
let value: unknown = "CIIT";

if (typeof value === "string") {
    console.log(value.toUpperCase());
}

Output: CIIT

Q8

What is an interface?

An interface describes the shape of an object. It specifies which properties and methods an object is expected to have.
interface Student {
    id: number;
    name: string;
}

const student: Student = {
    id: 101,
    name: "Priya"
};
Q9

What is a type alias?

A type alias creates a name for a type. It can describe primitives, unions, objects, function types, and other type expressions.
type CourseStatus = "Active" | "Completed" | "Pending";

let status: CourseStatus = "Active";
Q10

What is a union type?

A union type allows a value to be one of multiple specified types.
let studentId: number | string;

studentId = 101;
studentId = "STU102";

Both assignments are valid because the declared type allows either a number or a string.

3. Intermediate TypeScript Interview Questions

Q11

What is the difference between an interface and a type alias?

Both can describe object shapes. Interfaces can be extended and declaration-merged. Type aliases can directly express unions, intersections, primitives, tuples, and other type expressions. Both are useful, depending on the design.
interface Person {
    name: string;
}

interface Employee extends Person {
    salary: number;
}

type Status = "Active" | "Inactive";

type Point = {
    x: number;
    y: number;
};
Q12

What are optional properties?

Optional properties are marked with ?. They do not have to be present in every object of that type.
interface Employee {
    id: number;
    name: string;
    department?: string;
}

const employee: Employee = {
    id: 1,
    name: "Amit"
};
Q13

What are generics?

Generics allow functions, interfaces, and classes to work with different types while retaining type information.
function identity<T>(value: T): T {
    return value;
}

console.log(identity<number>(100));
console.log(identity<string>("TypeScript"));

Generics reduce duplicated logic while preserving useful type checking.

Q14

What is a type assertion?

A type assertion tells the TypeScript compiler to treat a value as a particular type. It does not perform a runtime conversion or verify that the value actually has that type.
const someValue: unknown = "Hello TypeScript";

const message = someValue as string;

console.log(message.toUpperCase());

Output: HELLO TYPESCRIPT

Q15

What are access modifiers?

TypeScript classes support public, private, and protected access modifiers. They control how class members can be accessed within TypeScript's type system.
class Employee {
    public name: string;
    private salary: number;
    protected department: string;

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

    public displayName(): void {
        console.log(this.name);
    }
}

TypeScript's private and protected modifiers are primarily compile-time restrictions. JavaScript's runtime private fields use syntax such as #salary.

Q16

What is an enum?

An enum defines a set of named constants. TypeScript also supports alternatives such as string literal unions, depending on the use case.
enum CourseStatus {
    Active,
    Completed,
    Pending
}

const status: CourseStatus = CourseStatus.Active;

console.log(status);

Output: 0, because numeric enums start at zero by default.

Q17

What is the never type?

The never type represents values that never occur. It is commonly used for functions that always throw or never finish through normal return.
function throwError(message: string): never {
    throw new Error(message);
}
Q18

What is type narrowing?

Type narrowing uses checks such as typeof, instanceof, or property checks to reduce a value's possible types within a particular code path.
function displayValue(value: string | number): void {
    if (typeof value === "string") {
        console.log(value.toUpperCase());
    } else {
        console.log(value.toFixed(2));
    }
}

displayValue("ciit");
displayValue(25);
Expected Output
CIIT
25.00
Q19

What are readonly properties?

A readonly property cannot normally be reassigned after initialization in accordance with the TypeScript type rules.
interface Course {
    readonly id: number;
    name: string;
}

const course: Course = {
    id: 101,
    name: "TypeScript"
};

course.name = "Advanced TypeScript";

// This would produce a TypeScript error:
// course.id = 102;
Q20

What are modules in TypeScript?

Modules allow code to be organized into files. An exported function, class, or type can be used by another module through import statements.
// MathUtils.ts
export function add(a: number, b: number): number {
    return a + b;
}

// App.ts
import { add } from "./MathUtils";

console.log(add(10, 20));

Expected output: 30.

4. Advanced TypeScript Interview Questions

Q21

What is the difference between Promise and async/await?

A Promise represents the eventual result of an asynchronous operation. Async/await provides syntax for working with Promises in a more sequential style. An async function always returns a Promise.
function getMessage(): Promise<string> {
    return Promise.resolve("Welcome to CIIT");
}

async function displayMessage(): Promise<void> {
    const message = await getMessage();
    console.log(message);
}

displayMessage();
Q22

What is the difference between Promise.all() and Promise.allSettled()?

Promise.all() Promise.allSettled()
Fulfills when all inputs fulfill. Waits for all inputs to settle.
Rejects if an input rejects. Reports each input's fulfillment or rejection.
Useful when every result is needed for success. Useful when every operation's outcome is needed.
Q23

What are utility types?

Utility types transform existing types into new types. Examples include Partial, Required, Pick, Omit, Readonly, and Record.
interface Student {
    id: number;
    name: string;
    email: string;
}

type StudentUpdate = Partial<Student>;

const update: StudentUpdate = {
    email: "student@example.com"
};

Partial<Student> makes the properties optional.

Q24

What is the difference between == and ===?

The == operator allows type coercion in many comparisons. The === operator compares without that coercion, checking both type and value for primitive values. Strict equality is generally preferred.
console.log(5 == "5");
console.log(5 === "5");
Expected Output
true
false
Q25

What is structural typing?

TypeScript primarily checks object compatibility based on the structure of their types. For ordinary object types, a value can be compatible when it contains the required properties and those properties have compatible types.
interface Named {
    name: string;
}

function greet(person: Named): void {
    console.log("Hello " + person.name);
}

const student = {
    name: "Rahul",
    course: "TypeScript"
};

greet(student);

The object has the required name property, so it can be passed to the function.

5. TypeScript Coding Interview Questions

CODE 01

Reverse a String

function reverseString(text: string): string {
    return text.split("").reverse().join("");
}

console.log(reverseString("CIIT"));
Expected Output
TIIC
CODE 02

Find the Largest Number

function findLargest(numbers: number[]): number | undefined {
    if (numbers.length === 0) {
        return undefined;
    }

    return Math.max(...numbers);
}

console.log(findLargest([10, 35, 20, 90, 40]));
Expected Output
90
CODE 03

Remove Duplicate Values

function removeDuplicates(numbers: number[]): number[] {
    return [...new Set(numbers)];
}

console.log(removeDuplicates([1, 2, 2, 3, 4, 4]));
Expected Output
[1, 2, 3, 4]
CODE 04

Check Palindrome

function isPalindrome(text: string): boolean {
    const normalized = text.toLowerCase();

    return normalized === normalized.split("").reverse().join("");
}

console.log(isPalindrome("madam"));
console.log(isPalindrome("hello"));
Expected Output
true
false

This simple example compares lowercase strings without spaces or punctuation normalization.

CODE 05

Calculate Factorial

function factorial(number: number): number {
    if (!Number.isInteger(number) || number < 0) {
        throw new Error("Enter a non-negative integer.");
    }

    let result = 1;

    for (let i = 2; i <= number; i++) {
        result *= i;
    }

    return result;
}

console.log(factorial(5));
Expected Output
120
CODE 06

Filter Passing Students

interface StudentResult {
    name: string;
    marks: number;
}

const students: StudentResult[] = [
    { name: "Rahul", marks: 85 },
    { name: "Priya", marks: 35 },
    { name: "Amit", marks: 72 }
];

const passed = students.filter(
    student => student.marks >= 40
);

console.log(passed.map(student => student.name));
Expected Output
["Rahul", "Amit"]

6. Scenario-Based Interview Questions

S1
How do you handle API failures?

Use appropriate rejection handling or try-catch with async/await. Check HTTP response status, validate returned data, and provide a suitable error message.

S2
How do you model a student record?

Define an interface or suitable type with properties such as student ID, name, course, and marks.

S3
How do you avoid duplicated code?

Create reusable functions, shared types, generic utilities, and modules with clear responsibilities.

S4
How do you validate API data?

Treat external data as untrusted and validate its structure at runtime. Type annotations alone do not validate JSON.

7. Interview Preparation Tips

Understand the Concept

Explain what a feature does and why you would use it.

Write Code Without Copying

Practise implementing examples independently.

Explain Your Decisions

Describe types, edge cases, trade-offs, and error handling.

Practise Follow-up Questions

Be ready to change the example when a new requirement is introduced.

Summary

  • Understand JavaScript fundamentals and TypeScript's type system.
  • Practise interfaces, type aliases, union types, generics, and narrowing.
  • Be comfortable with classes, modules, Promises, and async/await.
  • Write coding solutions using functions, arrays, and object types.
  • Explain validation, error handling, and runtime data checks.
  • Practise explaining your reasoning instead of memorizing answers only.
← Previous: Mini Projects