Skip to content

TypeScript and Modern JavaScript Interview Questions for MEAN Stack

25 TypeScript and Modern JavaScript questions with answers for mean stack roles — 9 easy, 12 medium, 4 hard.

About TypeScript and Modern JavaScript

TypeScript is the language of Angular and increasingly of Node.js backends too. This topic covers types, interfaces, generics, utility types, narrowing, decorators, strict compiler settings and the difference between Observables and Promises. Interviewers check whether you can model data safely, share types between frontend and backend, and avoid the common habit of hiding problems with any.

Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

Why does Angular use TypeScript, and what benefits does it bring to a MEAN project?

Save to ▾
Show answer
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Angular is written in TypeScript and relies on its types and decorators for components, dependency injection and templates. Types catch mistakes at compile time, improve editor autocompletion and make refactoring large codebases safer. In MEAN projects, you can share interfaces such as User or Order between the Express API and the Angular client.
02

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

Save to ▾
Show answer
Both describe the shape of data. Interfaces are open, so declarations with the same name merge, and they can be extended with extends, which suits object models and class contracts. Type aliases can describe unions, intersections, tuples, primitives and mapped types, such as type Status = 'active' | 'blocked'. Many teams use interfaces for object shapes like API models and type aliases for unions and utility compositions.
03

What are decorators in TypeScript and how does Angular use them?

Save to ▾
Show answer
Decorators are functions that attach metadata or behaviour to classes, properties, methods or parameters using the @ syntax. Angular uses them to mark classes as framework building blocks: @Component, @Directive, @Pipe and @Injectable, along with property decorators like @Input, @Output, @ViewChild and @HostListener. Angular's compiler reads this metadata at build time to generate efficient rendering and dependency injection code.
04

Explain optional chaining and nullish coalescing with examples.

Save to ▾
Show answer
Optional chaining (?.) stops evaluation and returns undefined if the value before it is null or undefined, so user?.address?.city never throws. Nullish coalescing (??) provides a fallback only for null or undefined, unlike || which also replaces 0, empty string and false. So settings.pageSize ?? 10 keeps a real value of 0. Both work in TypeScript and in Angular templates.
05

What is the difference between an Observable and a Promise?

Save to ▾
Show answer
A Promise represents one future value, starts executing immediately when created and cannot be cancelled natively. An Observable can emit zero, one or many values over time, is lazy so nothing happens until you subscribe, and can be cancelled by unsubscribing. Observables also offer operators like map, filter, debounceTime and switchMap. Angular's HttpClient, router events and reactive forms all expose Observables.
06

An API sometimes returns null for a nested field and the Angular app crashes with cannot read properties of undefined. How do you fix it properly?

Save to ▾
Show answer
Model the API response accurately in TypeScript, marking the field as optional or nullable, and keep strictNullChecks on so the compiler forces you to handle it. Use optional chaining in code and templates, provide defaults with ??, and show a fallback in the UI with @if. Also agree with the backend team on the contract, and validate responses at the boundary if the data is untrusted.
07

You need a dropdown value that can only be 'pending', 'shipped' or 'delivered'. How do you model it so invalid values are impossible?

Save to ▾
Show answer
Use a string literal union, type OrderStatus = 'pending' | 'shipped' | 'delivered', or a const array with as const and derive the type from it, so the list can also render the dropdown options. Type the component property and API model with OrderStatus. The compiler then rejects typos like 'shiped'. On the backend, mirror the same values with a Mongoose enum validator.
08

Define TypeScript interfaces for a paginated API response and use them in a service method.

Save to ▾
Show answer
A generic wrapper avoids repeating pagination fields. export interface Paginated<T> { items: T[]; page: number; totalPages: number; } export interface Product { _id: string; name: string; price: number; tags?: string[]; } getProducts(page = 1): Observable<Paginated<Product>> { return this.http.get<Paginated<Product>>('/api/products', { params: { page } }); }
09

Tell me about a time strong typing helped you catch a bug before it reached production.

Save to ▾
Show answer
Situation: we renamed the field amount to totalAmount in the orders API. Task: update the Angular app before release. Action: because our shared Order interface was typed and strict templates were on, the build failed in eleven places, including a payment summary I would have missed. I fixed each usage and added the change to the API changelog. Result: the release went out with no broken screens.
10

Explain the any, unknown and never types in TypeScript.

Save to ▾
Show answer
any switches off type checking, so any operation is allowed and errors move to runtime. unknown also accepts any value but forces you to narrow it with typeof, instanceof or a type guard before using it, making it the safe choice for parsed JSON or caught errors. never represents values that never occur, such as a function that always throws, and is used in exhaustive switch checks.
11

What are generics in TypeScript? Give an Angular-related example.

Save to ▾
Show answer
Generics let you write reusable code that works with many types while keeping type safety, using type parameters like T. For example, an ApiResponse<T> interface can wrap any payload, and a service method get<T>(url: string): Observable<T> returns correctly typed data. Angular's HttpClient.get<User[]>() uses generics so the component knows it receives an array of users, without casting.
12

What are TypeScript utility types such as Partial, Pick, Omit and Record used for?

Save to ▾
Show answer
Utility types transform existing types instead of duplicating them. Partial<User> makes all fields optional, useful for update payloads. Pick<User, 'id' | 'name'> selects fields, and Omit<User, 'password'> removes them, handy for safe API responses. Record<string, number> describes an object map with typed keys and values. Readonly<T> and Required<T> are also common, and they keep frontend and backend models consistent.
13

What is type narrowing and what are type guards?

Save to ▾
Show answer
Narrowing is TypeScript refining a broad type to a more specific one inside a code block based on checks. typeof, instanceof, the in operator, equality checks and discriminated union tags all narrow types. A custom type guard is a function returning a predicate like value is Admin, which tells the compiler the type after the check. This makes handling union types, such as API success or error responses, safe.
14

What do the strict compiler options in tsconfig.json do?

Save to ▾
Show answer
Setting strict to true enables a family of checks, including strictNullChecks, so null and undefined must be handled explicitly; noImplicitAny, which errors on untyped values; strictPropertyInitialization, which requires class fields to be initialised; and strictFunctionTypes. New Angular projects enable strict mode and strict templates by default, which catches many bugs early, though migrating an old non-strict project needs gradual fixes.
15

A teammate uses any everywhere to silence TypeScript errors. How would you address it?

Save to ▾
Show answer
Explain that any hides real bugs and removes autocompletion, then show concrete fixes: proper interfaces for API models, unknown with narrowing for untrusted data, and generics for reusable helpers. Enable the noImplicitAny compiler option and the ESLint no-explicit-any rule as a warning, fix the most critical files first, and add a review guideline. Keep the conversation constructive by pairing on one module together.
16

Write a generic TypeScript function that groups an array of items by a key.

Save to ▾
Show answer
Generics keep the result strongly typed. function groupBy<T, K extends keyof T>(items: T[], key: K): Record<string, T[]> { return items.reduce((acc, item) => { const group = String(item[key]); (acc[group] ||= []).push(item); return acc; }, {} as Record<string, T[]>); } interface Order { id: number; status: string } const byStatus = groupBy<Order, 'status'>(orders, 'status'); K extends keyof T ensures only real property names are accepted.
17

Write a custom type guard to check whether an API response is an error.

Save to ▾
Show answer
A type predicate narrows the union. type ApiError = { error: true; message: string }; type ApiSuccess<T> = { error: false; data: T }; type ApiResult<T> = ApiError | ApiSuccess<T>; function isApiError<T>(res: ApiResult<T>): res is ApiError { return res.error === true; } if (isApiError(result)) { console.error(result.message); } else { render(result.data); } Inside each branch TypeScript knows exactly which fields exist.
18

Write a debounced search helper in TypeScript using a closure.

Save to ▾
Show answer
A typed debounce keeps argument types. function debounce<A extends unknown[]>(fn: (...args: A) => void, ms = 300) { let timer: ReturnType<typeof setTimeout> | undefined; return (...args: A) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), ms); }; } const search = debounce((term: string) => console.log('search', term), 400); search('ang'); In Angular you would usually use the RxJS debounceTime operator instead.
19

Show the tsconfig settings you would enable for a strict Node.js Express API.

Save to ▾
Show answer
A typical strict configuration: { "compilerOptions": { "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext", "outDir": "dist", "rootDir": "src", "strict": true, "noUncheckedIndexedAccess": true, "esModuleInterop": true, "skipLibCheck": true, "sourceMap": true }, "include": ["src"] } noUncheckedIndexedAccess adds undefined to indexed lookups, catching missing keys.
20

How do you approach learning a new framework version or language feature on the job?

Save to ▾
Show answer
Situation: our team decided to adopt Angular signals in new features. Task: I had to use them in a sprint while still delivering. Action: I read the official guide, built a small sample, compared it with our RxJS patterns, then implemented one component and asked a senior to review. I shared a short note with examples for the team. Result: my component became the reference pattern for later features.
21

How do you set and enforce TypeScript coding standards across a development team?

Save to ▾
Show answer
Situation: our MEAN team had inconsistent code, with some files strict and others full of any. Task: as a senior developer I was asked to standardise it. Action: I proposed a shared tsconfig with strict mode, ESLint with typescript-eslint rules, Prettier and a pre-commit hook, discussed exceptions with the team, and fixed violations module by module. Result: review comments on style dropped sharply and type-related bugs in QA reduced.
22

What are discriminated unions and why are they useful?

Save to ▾
Show answer
A discriminated union is a union of object types that share a literal property, the tag, such as type Result = { status: 'ok'; data: User } | { status: 'error'; message: string }. Checking result.status narrows the type, so TypeScript knows which fields exist in each branch. Combined with a never check in the default case, the compiler warns you when a new variant is added but not handled.
23

Frontend and backend models keep drifting apart, causing runtime bugs. How would you keep them in sync in a MEAN project?

Save to ▾
Show answer
Share types from a single source. In a monorepo, for example with Nx, put DTO interfaces in a shared library used by both the Express API and Angular. Alternatively generate an OpenAPI spec from the backend and generate Angular client types from it, or define schemas once with zod and infer types. Add contract tests in CI so a breaking change fails the build.
24

You are migrating a large JavaScript Node.js codebase to TypeScript. How would you approach it?

Save to ▾
Show answer
Migrate gradually. Add TypeScript with allowJs so JS and TS files coexist, start with loose settings and turn on strict options step by step. Convert leaf modules such as utilities and models first, then services and routes. Install type packages like @types/express, define shared interfaces for request and response shapes, and run type checks in CI. Avoid a big-bang rewrite that blocks feature work.
25

Write an exhaustive switch over a union type using never.

Save to ▾
Show answer
The never check makes the compiler flag unhandled cases. type Shape = { kind: 'circle'; r: number } | { kind: 'square'; side: number }; function area(s: Shape): number { switch (s.kind) { case 'circle': return Math.PI * s.r ** 2; case 'square': return s.side ** 2; default: { const unreachable: never = s; throw new Error(`Unknown shape ${unreachable}`); } } } Adding a triangle variant now causes a compile error until it is handled.

Frequently asked questions

How important is TypeScript and Modern JavaScript in MEAN Stack interviews?

TypeScript is the language of Angular and increasingly of Node.js backends too. This topic covers types, interfaces, generics, utility types, narrowing, decorators, strict compiler settings and the difference between Observables and Promises. Interviewers check whether you can model data safely, share types between frontend and backend, and avoid the common habit of hiding problems with any.

How should I use the TypeScript and Modern JavaScript sheet?

Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.