Information Technology
TypeScript Interview Questions & Answers
A strictly typed superset of JavaScript that scales efficiently.
Classes: Access Modifiers, Abstract Classes & Implements
All 10 questionspublic (the default) makes a member accessible from anywhere; private restricts access to only within the declaring class itself; protected allows access within the declaring class…
The 'private' keyword is a TypeScript-only, compile-time restriction — it's erased at compile time and the field is still a regular accessible property in the emitted JavaScript. T…
Mark a class with the abstract keyword to prevent it from being instantiated directly with 'new' — it exists only to be extended, typically providing shared implementation plus one…
implements requires a class to satisfy an interface's shape — providing all its declared members — without inheriting any implementation or behavior. extends inherits actual behavi…
Prefixing a constructor parameter with an access modifier (public, private, protected, or readonly) automatically declares a class property of that name AND assigns the parameter's…
Conditional Types
All 10 questions- What is the basic syntax of a conditional type, and how does it resemble a ternary expression? Beginner
A conditional type has the form `T extends U ? X : Y` — evaluated at the type level, it resolves to X if T is assignable to U, and Y otherwise, mirroring the syntax and logic of a…
Combine a conditional type with the 'infer' keyword to capture and name the array's element type only when T actually matches the array shape.
infer introduces a new type variable within the 'extends' clause of a conditional type, letting TypeScript capture and name a piece of the matched type structure for use in the tru…
When the checked type T is a naked type parameter (not wrapped in something like [T]) and you pass a union as T, the conditional type automatically distributes over each member of…
Wrap both sides of 'extends' in a single-element tuple (like [T] extends [U]), which makes T no longer a 'naked' type parameter — this disables the automatic distribution behavior…
Declaration Files
All 10 questionsA declaration file contains only type information — interfaces, type aliases, and function/variable signatures — with no runtime implementation code. It lets TypeScript type-check…
- How do you get type definitions for a popular JavaScript library that doesn't ship its own types? Beginner
Install the corresponding community-maintained package from DefinitelyTyped, prefixed with @types/ — TypeScript automatically discovers and uses these type packages from node_modul…
declare tells TypeScript 'trust me, this exists at runtime somewhere else' — it describes a type shape without providing (or requiring) any implementation, and is erased entirely f…
- How do you write a declaration file for a library that attaches itself to the global 'window' object? Intermediate
Use a 'declare global' block (inside a module file) or a plain ambient declaration (in a non-module .d.ts) to extend the global scope's type, describing the shape the library adds…
'export =' in a .d.ts describes a module whose entire export is a single value (common in older CommonJS libraries), rather than a set of named exports — consumers then use 'import…
Decorators
All 10 questionsA decorator is a special kind of declaration prefixed with @ that can be attached to a class, method, property, or parameter to observe, modify, or replace its definition — it's es…
- What must be enabled in tsconfig.json to use the (legacy, 'experimental') decorator syntax? Beginner
Set "experimentalDecorators": true in compilerOptions — without it, the @ decorator syntax produces a compile error under the legacy decorator implementation used by frameworks lik…
A class decorator receives the class's constructor function as its argument and can inspect it, add static properties, or return a brand-new constructor that replaces the original…
A method decorator receives the target (the class prototype), the method's name, and its PropertyDescriptor (which includes the original 'value' function) — it can wrap or replace…
- What is a decorator factory, and why would you use one instead of a plain decorator function? Intermediate
A decorator factory is a function that RETURNS a decorator, letting you pass custom configuration arguments to customize the decorator's behavior per-use — plain decorators can't a…
Discriminated Unions & Exhaustiveness Checking
All 10 questionsA discriminated union is a union of object types that all share a common literal-typed property (the discriminant, often called 'kind' or 'type'). Checking that property's value in…
Switch on the discriminant property; inside each case block, TypeScript automatically narrows the variable to the specific variant matching that case's literal value, giving you sa…
- What is exhaustiveness checking, and how does the 'never' type enable it in a default case? Intermediate
Exhaustiveness checking uses the fact that after handling every known variant, the remaining type should be 'never' (impossible) — assigning the narrowed value to a variable typed…
- How would you model API response states (loading, success, error) as a discriminated union? Intermediate
Define a union where each state variant has the same discriminant key (e.g. 'status') with a different literal value, plus only the data relevant to that specific state — this prev…
- Can you use a discriminant that isn't a string literal, like a number or boolean literal type? Intermediate
Yes — the discriminant just needs to be a literal type (string, number, or boolean literal) that's unique across the union's variants; TypeScript narrows equally well whether you c…
Enums
All 10 questionsA numeric enum assigns sequential integer values starting at 0 to each member by default, unless you explicitly assign a starting value — subsequent members then auto-increment fro…
A string enum explicitly assigns a distinct string literal to each member (no auto-incrementing), which makes debugging easier since logged/serialized values are meaningful text ra…
Numeric enums generate a two-way lookup object at runtime — you can go from name to value AND from value back to name (Direction[0] === 'Up'). String enums only generate a one-way…
- What is a 'const enum' and how does it differ from a regular enum in the compiled output? Intermediate
A const enum is fully inlined at every usage site during compilation and produces NO actual runtime object at all — usages of Direction.Up are replaced directly with the literal va…
- How do computed and constant enum members work when mixing string and numeric-style initialization? Intermediate
Enum members can be constant (a literal, or computed from prior members) or 'computed' (derived from a non-constant expression) — TypeScript requires that any UNINITIALIZED member…
Function Types, Overloads & Optional/Default Parameters
All 10 questionsUse arrow-style syntax `(param: Type) => ReturnType` to describe a function's shape, specifying each parameter's type and the return type.
Add a '?' after the parameter name; TypeScript automatically adds 'undefined' to its type, and optional parameters must come after all required parameters in the parameter list.
- How do you give a function parameter a default value, and how does TypeScript infer its type? Beginner
Assign a default value directly in the parameter list using '='; TypeScript infers the parameter's type from the default value's type unless you also add an explicit annotation, an…
- What are function overloads, and how do they let a single function name handle multiple different call signatures? Intermediate
You declare multiple overload signatures (no implementation) followed by one general implementation signature that's compatible with all of them; TypeScript uses the overload signa…
- How do rest parameters work with type annotations, and what type must the annotation be? Intermediate
A rest parameter (prefixed with '...') collects any remaining arguments into an array, so its type annotation must be an array type (or tuple type for fixed-shape variadic argument…
Generics
All 10 questions'any' disables type checking entirely, losing all safety and autocomplete. Generics let a function or type work with MULTIPLE specific types while preserving the actual relationshi…
Add ` ` (or any name) right after the function name to declare a type parameter, then use T within the parameter and return types; you can let TypeScript infer T from the arguments…
- How do you constrain a generic type parameter using 'extends' to require it has certain properties? Intermediate
Write ` ` to restrict T to only types that are assignable to SomeShape, letting you safely access SomeShape's properties inside the function while still preserving T's more specifi…
- How do you use a generic type parameter to constrain a second parameter to be a valid key of the first? Intermediate
Use ` ` — this lets a function like a safe property-getter accept any key that ACTUALLY exists on T, catching typos or invalid keys at compile time, and lets the return type be pre…
- How do you provide a default type for a generic parameter, similar to a default function parameter? Intermediate
Write ` ` after the type parameter name; if the caller doesn't explicitly specify T and it can't be inferred from context, the default type is used instead, similar in spirit to de…
Index Signatures & Record Types
All 10 questionsAn index signature describes the type of ALL properties an object can have when the exact set of key names isn't known ahead of time, using the syntax `{ [key: string]: ValueType }…
- What is the built-in Record<K, V> utility type, and how does it relate to an index signature? Beginner
Record is a built-in utility type equivalent to `{ [key in K]: V }` — it's the more concise, commonly preferred way to express a dictionary-like object type where K is typically a…
- How do you combine an index signature with specific, explicitly-named required properties? Intermediate
You can mix known properties with an index signature, but every explicitly-named property's type must be ASSIGNABLE to the index signature's value type, since the index signature e…
By default, TypeScript trusts the index signature's promise and types every access (even to keys that may not exist) as the declared value type, WITHOUT undefined — this is technic…
- How do you use a Record type with a union of string literals as keys to enforce that ALL cases are handled? Intermediate
Record requires an object literal assigned to it to include EVERY member of the union as a key — omitting one causes a compile error, making it a lightweight way to enforce exhaust…
Mapped Types
All 10 questionsA mapped type generates a new object type by iterating over the keys of an existing type T (via `keyof T`) and applying a transformation to each property's type, letting you derive…
Partial is implemented as `{ [K in keyof T]?: T[K] }` — it maps over every key of T and adds a '?' to make each property optional, producing a version of T where every field can be…
By default, a mapped type COPIES existing modifiers ('?' and readonly) from the source type; explicitly writing `-?` or `-readonly` REMOVES that modifier from every mapped property…
Adding `as NewKeyExpression` after the `K in keyof T` clause lets you transform the resulting property NAME (not just its value type) — commonly combined with template literal type…
Combine key remapping with a conditional expression in the 'as' clause: for keys you want to KEEP, map to their normal name; for keys you want to EXCLUDE, map to 'never' — TypeScri…
Migrating JavaScript to TypeScript
All 10 questions- What is the recommended first step when migrating an existing JavaScript project to TypeScript? Beginner
Add a tsconfig.json with 'allowJs': true and 'checkJs': false (or start with a very lenient config), rename files gradually from .js to .ts rather than all at once, and let the pro…
allowJs lets the TypeScript compiler process plain .js files alongside .ts files in the same project, so you can incrementally rename files to .ts one at a time while the rest of t…
With checkJs enabled (or a per-file '// @ts-check' comment), TypeScript type-checks .js files using JSDoc-style comments as the source of type information, letting you get real typ…
Enabling full strict mode on an existing large JavaScript codebase typically surfaces hundreds or thousands of pre-existing implicit-any and null-safety issues all at once, which i…
- How do you handle a third-party JavaScript dependency that has no available type definitions during migration? Intermediate
Either install a community @types package if one exists, or write a minimal ambient declaration yourself (a .d.ts file with `declare module 'library-name';`), which effectively typ…
Modules
All 10 questionsTypeScript's import/export statements are (mostly) standard ES Module syntax with type-only extensions layered on top; the 'module' compiler option in tsconfig.json controls what a…
'import type' explicitly imports only type information, which the compiler completely erases from the output JavaScript — useful for making it clear an import has zero runtime cost…
Without esModuleInterop, importing a CommonJS module that exports a single function/value (via module.exports = x) using ES-style `import x from 'module'` syntax doesn't work corre…
- How does path mapping via the 'paths' compiler option let you use cleaner, absolute-style import paths? Intermediate
The 'paths' option (used together with 'baseUrl') lets you define custom import aliases (like '@/components/*') that TypeScript resolves during type-checking — though note the bund…
- What is 'isolatedModules' and why do some tools (like Babel, esbuild, or swc) require it to be enabled? Intermediate
isolatedModules ensures every file can be safely transpiled INDEPENDENTLY, one file at a time, without needing full cross-file type information — some fast, non-typechecking compil…
Namespaces & Declaration Merging
All 10 questionsA namespace groups related code under a single named container using the 'namespace' keyword, generating a nested object at runtime — it was TypeScript's original way to organize c…
Just like a module, everything declared inside a namespace is private to that namespace by default; only explicitly 'export'ed members become accessible via NamespaceName.memberNam…
- What is declaration merging, and how does TypeScript combine multiple 'interface' declarations with the same name? Intermediate
When you declare an interface with the same name multiple times (even in different files), TypeScript automatically MERGES all their members into a single combined interface, rathe…
- How does merging work between a namespace and a class (or function) sharing the same name? Intermediate
A namespace can merge with a class, function, or enum of the same name declared alongside it, effectively attaching static-like members or nested types to that class/function/enum…
- How do you merge a namespace with an enum to add extra static-like helper functionality to that enum? Intermediate
Declare a namespace with the same name as the enum, and add exported functions inside it — TypeScript merges the namespace's members onto the enum object, letting you attach utilit…
Never, Unknown & Void Types
All 10 questions'void' indicates a function's return value should be IGNORED by callers, even if the function actually returns undefined (or nothing at all) at runtime — it's specifically about th…
'unknown' represents a value whose type isn't known yet — like 'any', it can hold ANY value, but unlike 'any', you CANNOT perform any operations on an 'unknown' value (property acc…
- What does the 'never' type represent, and when does a function's return type become 'never'? Beginner
'never' represents a value that can NEVER actually occur — a function's return type is inferred as 'never' when it always throws an exception, always enters an infinite loop, or ot…
'never' is TypeScript's bottom type — a subtype of EVERY other type, but no type (except never itself) is a subtype of it. This means never is compatible everywhere it's expected,…
- How does 'unknown' interact with union types, and why does `unknown | T` always simplify to just 'unknown'? Intermediate
Since 'unknown' is TypeScript's top type — every other type is assignable TO it — combining it with anything in a union absorbs that other type entirely, because 'unknown' already…
Nullability: strictNullChecks, Optional Chaining & Nullish Coalescing
All 10 questions- What does the 'strictNullChecks' compiler option change about how null and undefined are treated? Beginner
Without strictNullChecks, null and undefined are silently assignable to EVERY type (a major source of runtime errors). With it enabled, null and undefined become distinct types tha…
?. safely accesses a property, calls a method, or indexes into a value, short-circuiting and returning 'undefined' immediately if the value right before it is null or undefined, in…
?? only falls back to its right-hand side when the left-hand side is SPECIFICALLY null or undefined; || falls back for ANY falsy value, including 0, '', NaN, and false — which can…
- How does the non-null assertion operator (!) differ from actually checking and narrowing a value? Intermediate
The ! operator tells the COMPILER 'trust me, this is definitely not null/undefined here', silencing the type error WITHOUT adding any runtime check — if you're wrong, it still thro…
Chain ?. through the potentially-missing path, then use ?? immediately after to provide a fallback specifically for the case where the whole chain resolved to undefined (either bec…
Primitive Types, Arrays & Tuples
All 11 questionsTypeScript's core primitives are string, number, boolean, null, undefined, symbol, and bigint — annotate a variable using a colon followed by the type name after its identifier.
- How do you type an array of a specific element type, and what are the two equivalent syntaxes? Beginner
Use either `Type[]` (more common, especially for simple types) or the generic `Array ` syntax (sometimes preferred for more complex or nested generic types, for readability) — both…
A tuple is a fixed-LENGTH array where each position has its own SPECIFIC type, unlike a regular array type where every element must share the same single type — tuples are declared…
- How do you make a tuple element optional, and how does that affect the tuple's minimum required length? Intermediate
Add '?' after a tuple element's type, similar to optional function parameters — optional elements must come after all required elements, and TypeScript correctly tracks that the tu…
- How do labeled tuple elements improve readability and editor tooling compared to unlabeled tuples? Intermediate
Adding a name before each element's type (like `[x: number, y: number]`) doesn't change runtime behavior at all, but significantly improves editor autocomplete/hover tooltips and f…
Readonly, const Assertions & Immutability
All 10 questions- How does the 'readonly' modifier on an interface property differ from using 'const' for a variable? Beginner
'const' prevents REASSIGNING a variable binding itself, but doesn't stop you from mutating an object it points to; 'readonly' on a property prevents REASSIGNING that specific prope…
Prefix the array type with 'readonly', or use the generic `ReadonlyArray ` — both prevent index assignment AND remove access to mutating methods like push, pop, splice, and sort fr…
'as const' locks every property to its most specific literal type (rather than the general widened type like 'string' or 'number') AND makes every property (recursively) readonly,…
'readonly' is a compile-time-only restriction, completely erased from the emitted JavaScript — at runtime, the property is a perfectly normal, mutable value, so any code that bypas…
- How does 'as const' behave differently when applied to an array literal versus a plain object literal? Intermediate
Applied to an array literal, 'as const' converts it from a general array type (like number[]) into a fixed-length, readonly TUPLE type with each element's specific literal type pre…
Structural Typing & Duck Typing
All 10 questionsStructural typing determines type compatibility based purely on the SHAPE of a type — what properties/methods it has — rather than its declared NAME or explicit inheritance relatio…
Duck typing (the phrase's origin) means a value's suitability is judged by whether it HAS the behavior/shape you need, not by what it's formally declared to be — TypeScript's struc…
- What is 'excess property checking', and why does it seem to contradict pure structural typing at first glance? Intermediate
When assigning an OBJECT LITERAL directly (not through a variable) to a typed variable/parameter, TypeScript performs a STRICTER check that flags any extra properties not in the ta…
- How does structural typing handle two interfaces that are 'shape-identical' but declared completely independently? Intermediate
Since compatibility is purely shape-based, two independently-declared interfaces (or a class and an interface, or two unrelated classes) with IDENTICAL public shapes are considered…
A function with FEWER declared parameters is structurally compatible where MORE are expected (since it simply ignores extra arguments passed to it, which is safe), but a function r…
Template Literal Types
All 10 questions- What is a template literal type, and how does its syntax resemble a JavaScript template literal? Beginner
A template literal type uses the same backtick syntax as a runtime template literal, but with TYPES embedded inside `${...}` instead of values — it produces a new string literal ty…
- How does embedding a union of literal types inside a template literal type produce a new union? Beginner
When you embed a union type inside `${...}`, TypeScript computes the CROSS PRODUCT of every combination, producing a new union of every possible resulting string literal — this hap…
These four built-in generic utility types transform a string literal type's CASING at the type level (mirroring their runtime string method equivalents), and are most commonly comb…
Build a template literal type describing the exact expected character pattern using nested unions for each character position — while genuinely complex patterns (like arbitrary-len…
Within a mapped type's key-remapping 'as' clause, you can construct a NEW property name using a template literal type that references the original key (often combined with Capitali…
tsconfig & Compiler Options
All 10 questions- What is the purpose of the tsconfig.json file, and what does the 'compilerOptions' key control? Beginner
tsconfig.json marks a directory as the root of a TypeScript project and configures how the compiler behaves — 'compilerOptions' specifically holds settings controlling type-checkin…
'target' specifies which ECMAScript version the compiled JavaScript output should conform to — newer language features (like optional chaining, async/await, or classes) get automat…
- What does the 'strict' compiler option actually enable, and which individual flags does it bundle together? Intermediate
'strict': true is a shorthand that enables a whole family of individual strictness flags at once, including noImplicitAny, strictNullChecks, strictFunctionTypes, strictBindCallAppl…
'include' specifies glob patterns for files/directories to bring INTO the project (with 'exclude' subtracting specific patterns back out, commonly node_modules by default); 'files'…
Both flags flag declared-but-never-used local variables or function parameters as compile errors, helping catch dead code and leftover debugging variables; to intentionally allow a…