This page is for developers preparing for TypeScript rounds, whether you are a fresher who has written a few React or Node projects or an engineer with several years of production code. It was compiled by VidhaiX trainers who run mock interviews for frontend, full-stack and automation roles, and it reflects the questions we see candidates struggle with most.
In 2026, interviewers at Indian product companies, service companies and startups rarely ask you to recite syntax. They probe whether you understand how the type system reasons: narrowing, generics with constraints, conditional and mapped types, strict compiler flags, where types end and runtime validation begins, and how modern tooling such as Node type stripping and the native Go compiler changes builds. Questions are grouped into freshers, intermediate, experienced (3+ years) and scenario-based rounds. Each answer explains what a strong response covers and the traps that cost candidates the round.
How to Prepare for a TypeScript Interview
- Turn on `strict` and `noUncheckedIndexedAccess` in a personal project and fix every error by hand, without reaching for `any` or non-null assertions, so you can explain each fix aloud.
- Write three utility types from scratch, such as your own `Partial`, `ReturnType` and a deep readonly, then compare them with the built-in definitions in lib.es5.d.ts.
- Model a real API response as a discriminated union, add an exhaustive `switch` with a `never` check, then add a new variant and watch the compiler point at every place to update.
- Validate an external payload with Zod, derive the static type with `z.infer`, and be ready to explain why compile-time types alone cannot protect you from bad JSON.
- Set up a small monorepo with project references and `tsc -b`, then measure build time with `--extendedDiagnostics` so you can talk about build performance with real numbers.
- Run a TypeScript file directly with Node type stripping and note which syntax fails, such as enums and parameter properties, and how `erasableSyntaxOnly` catches it earlier.
- Practise explaining generic code out loud on a whiteboard: interviewers care more about your reasoning on inference and constraints than about memorising obscure type puzzles.
TypeScript Interview Questions for Freshers
12 questions
Q1.What problem does TypeScript actually solve, and what does it not do at runtime?
TypeScript adds a static type checker on top of JavaScript. It catches mistakes such as calling a method on a possibly undefined value, passing the wrong shape to a function or misspelling a property, before the code runs. It also powers editor autocomplete and safe refactoring across large codebases.
The trap is believing types exist at runtime. They are erased during compilation, so a wrongly typed API response still crashes. Strong candidates say types are a design-time contract and that untrusted input needs runtime validation.
Q2.What is the difference between `type` and `interface`, and when do you pick one over the other?
Both can describe object shapes, and for most objects they are interchangeable. An interface can be reopened through declaration merging and is extended with extends, which gives clearer error messages and can be cheaper for the checker on large hierarchies. A type alias can name anything: unions, tuples, primitives, mapped and conditional types.
A sensible team rule is interfaces for public object contracts and types for unions and computed types. A weak answer claims one is strictly better; interviewers want the trade-offs.
Q3.Explain `any`, `unknown` and `never`. Why do reviewers push back on `any`?
any switches off checking: you can call anything on it and it silently spreads to everything it touches. unknown is the safe top type: anything can be assigned to it, but you must narrow it before using it. never is the bottom type, representing values that cannot exist, such as the return of a function that always throws or the leftover case after exhaustive narrowing.
Reviewers dislike any because it hides bugs without any warning. Use unknown for untrusted data and narrow or validate it.
Q4.What does structural typing mean in TypeScript, and how is it different from Java or C#?
TypeScript compares types by shape, not by name. If an object has all the properties a type requires with compatible types, it is assignable, even if it was never declared as that type. Java and C# are nominal: a class must explicitly implement an interface.
A good answer mentions the consequence: two unrelated types with identical shapes, such as UserId and OrderId both being string, are interchangeable, which is why teams use branded types when mixing them up would be a real bug.
Q5.What is type inference, and when should you write explicit type annotations anyway?
The compiler infers types from initialisers, return statements and context, so const count = 0 needs no annotation. Over-annotating adds noise and can widen types you wanted narrow.
Annotate where the type is a contract: exported function parameters and return types, public APIs of a module, and empty values such as useState<User | null>(null) or [] where inference has nothing to work with. Explicit return types on exported functions also stop accidental changes from leaking to callers and can speed up type checking in large projects.
Q6.What are union and intersection types? Give a practical example of each.
A union A | B means a value is one of several types, such as string | number or "idle" | "loading" | "error". You can only use members common to all options until you narrow. An intersection A & B means a value has everything from both types, which is useful for combining a base entity with extra fields, like User & { permissions: string[] }.
A common trap is intersecting incompatible primitives, which produces never, and expecting intersections of functions to behave like unions.
Q7.What is narrowing, and which built-in narrowing techniques do you use day to day?
Narrowing is how the compiler refines a broad type to a specific one based on control flow. Everyday tools are typeof checks for primitives, instanceof for classes, the in operator for checking a property exists, equality checks against literals or null, and truthiness checks.
Strong candidates mention that narrowing follows control flow, so an early return narrows everything after it, and that narrowing can be lost inside callbacks when the variable is mutable, because the compiler cannot prove it was not reassigned.
function format(input: string | number | null) {
if (input === null) return '-'
if (typeof input === 'number') return input.toFixed(2)
return input.trim() // input is string here
}Q8.What are literal types and what does `as const` do?
A literal type is a single exact value as a type, such as "GET" or 404. By default the compiler widens let method = "GET" to string. as const stops that widening: strings stay literal, arrays become readonly tuples and object properties become readonly literals.
It is commonly used to derive a union from a constant array, which keeps the runtime list and the type in sync from one source of truth instead of maintaining both by hand.
const ROLES = ['admin', 'trainer', 'learner'] as const
type Role = (typeof ROLES)[number] // 'admin' | 'trainer' | 'learner'
function isRole(value: string): value is Role {
return (ROLES as readonly string[]).includes(value)
}Q9.How do optional properties, `undefined` and `null` differ, and what does `strictNullChecks` change?
Without strictNullChecks, null and undefined are assignable to every type, so the compiler never warns about the most common runtime crash. With it on, they become distinct types you must handle explicitly.
An optional property name?: string may be missing or undefined; name: string | undefined must be present but can be undefined. With exactOptionalPropertyTypes the compiler treats these differently. Interviewers also like hearing that ?. and ?? are the idiomatic ways to deal with possibly missing values.
Q10.What does the non-null assertion operator `!` do, and why is it risky?
Writing value! tells the compiler to treat a possibly null or undefined value as definitely present. It emits no runtime check, so if you are wrong the code crashes exactly as plain JavaScript would.
It is acceptable when you have knowledge the compiler cannot see, such as an element guaranteed by your own markup, but a codebase full of ! is hiding real null handling. Better options are narrowing with an explicit check, throwing a clear error, or fixing the type at its source.
Q11.Should you use an `enum` or a union of string literals?
A string literal union like "draft" | "published" has zero runtime cost, works naturally with JSON and is fully erasable. A regular enum generates a runtime object, numeric enums accept arbitrary numbers in some cases, and const enum has pitfalls with isolated compilation.
In 2026 most teams prefer unions, often paired with an as const object when they need a runtime list of values. Enums also cannot run under Node type stripping or erasableSyntaxOnly, which pushes new code further towards unions.
Q12.What does `tsconfig.json` control, and which options should every new project set?
tsconfig.json defines which files belong to the project and how they are checked and emitted: target language level, module system, module resolution, libraries, JSX handling and strictness. For a new project, a strong baseline is strict: true, noUncheckedIndexedAccess, verbatimModuleSyntax, isolatedModules and skipLibCheck.
Candidates should also explain that in many modern setups a bundler or runtime strips types, so tsc runs with noEmit purely as a type checker in CI.
TypeScript Intermediate Interview Questions
12 questions
Q13.How do you write a custom type guard, and what is an assertion function?
A type guard is a function returning value is T; when it returns true, the caller narrows to T. An assertion function returns asserts value is T and throws otherwise, so code after the call is narrowed. Since TypeScript 5.5, simple filters like arr.filter(x => x !== undefined) can infer a type predicate automatically.
The trap is that the compiler trusts your predicate blindly. A guard that checks only one field can lie, so guards on external data should be thorough or replaced by a schema validator.
interface Course { id: string; title: string }
function isCourse(v: unknown): v is Course {
return typeof v === 'object' && v !== null &&
typeof (v as Course).id === 'string' &&
typeof (v as Course).title === 'string'
}Q14.What is a discriminated union, and how do you enforce exhaustive handling?
A discriminated union is a union of object types that share a literal property, such as status or kind. Checking that property narrows to the exact variant, so each branch sees only the fields that exist for it.
To enforce exhaustiveness, assign the value to never in the default branch. When someone adds a new variant, every unhandled switch fails to compile. Interviewers like this because it shows you use the compiler as a refactoring tool, not just a linter.
type Payment =
| { kind: 'upi'; vpa: string }
| { kind: 'card'; last4: string }
| { kind: 'emi'; months: number }
function label(p: Payment): string {
switch (p.kind) {
case 'upi': return p.vpa
case 'card': return 'Card ' + p.last4
case 'emi': return p.months + ' month EMI'
default: {
const unreachable: never = p
throw new Error('Unhandled payment ' + JSON.stringify(unreachable))
}
}
}Q15.How do generics with constraints work? Write a type-safe `getProperty` function.
Generics let a function or type work over many types while preserving the relationship between inputs and outputs. A constraint with extends limits what callers can pass, and lets you use known members inside the body.
In getProperty, K extends keyof T restricts keys to real properties of the object, and the return type T[K] is an indexed access type, so the caller gets the exact property type back. A weak answer returns any or uses string for the key and loses that link.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key]
}
const batch = { name: 'Playwright', seats: 20 }
const seats = getProperty(batch, 'seats') // number
// getProperty(batch, 'fees') -> compile errorQ16.Walk me through `Partial`, `Required`, `Pick`, `Omit` and `Record`. Where have you used them?
Partial<T> makes all properties optional, which fits patch payloads. Required<T> does the opposite. Pick<T, K> keeps selected keys and Omit<T, K> removes them, which is handy for deriving a create DTO from an entity without the id and timestamps. Record<K, V> builds an object type with known keys, such as a lookup from status to label.
A sharper answer notes that Omit does not check that the keys exist on T, so typos pass silently, and that deriving types beats duplicating them.
Q17.What do `ReturnType`, `Parameters` and `Awaited` give you, and why are they useful?
ReturnType<typeof fn> extracts a function return type and Parameters<typeof fn> gives its argument tuple. Awaited<T> recursively unwraps promises, so Awaited<ReturnType<typeof fetchUser>> gives the resolved user type of an async function.
They let you derive types from the code that actually produces the data, such as a server action or a database query helper, instead of maintaining a parallel interface that drifts. The caution is not to overuse them across module boundaries, where an explicit named type is easier to read.
Q18.What does the `satisfies` operator do, and how is it different from a type annotation or `as`?
An annotation such as const config: Config = {...} checks the value but widens the variable to Config, losing the precise literal keys and values. as Config is an assertion and can hide errors. satisfies Config checks the value against the type while keeping the narrower inferred type.
That is ideal for configuration objects and route maps: you get errors for typos or missing keys, and autocomplete still knows exactly which keys exist. Combining as const satisfies T gives both readonly literals and validation.
type Route = { path: string; auth: boolean }
const routes = {
home: { path: '/', auth: false },
dashboard: { path: '/dashboard', auth: true },
} satisfies Record<string, Route>
routes.dashboard.path // ok, and routes.missing is an errorQ19.How does `keyof` and `typeof` work at the type level, and how do indexed access types fit in?
At the type level, typeof value gives the type of an existing runtime value, keyof T gives a union of its property keys, and T[K] reads the type of a property. Together they let you derive types from real objects instead of restating them.
For example, keyof typeof translations produces the union of valid translation keys straight from the object. A common trap is forgetting that keyof on a type with a string index signature returns string | number, because numeric keys are converted to strings in JavaScript.
Q20.What does `noUncheckedIndexedAccess` change, and is it worth enabling?
With it on, reading from an index signature or an array by index adds undefined to the type. So scores[i] is number | undefined and map[key] is V | undefined. Without it, the compiler pretends every lookup succeeds, which is a common source of production undefined crashes.
It adds some friction, especially in loops, but for...of, destructuring with defaults and explicit checks handle most cases. Most teams with strict codebases enable it; adopting it late in a large project is best done module by module.
Q21.Explain the difference between `moduleResolution` set to `bundler` and `nodenext`.
nodenext models how Node actually resolves modules: it reads type and exports in package.json, distinguishes ESM from CommonJS, and requires explicit file extensions on relative ESM imports. Use it for code Node runs directly or for published libraries.
bundler models tools such as Vite, Next.js and esbuild: it honours exports but allows extensionless relative imports, as bundlers do. Choosing bundler for a Node service is a classic mistake, because it compiles cleanly and then fails at runtime with missing module errors.
Q22.What is declaration merging, and when have you used module augmentation?
Declaration merging means multiple declarations with the same name combine. Two interface declarations merge their members, and namespaces can merge with functions, classes or enums. Type aliases never merge.
The practical use is module augmentation: adding fields to a library type, such as extending Express Request with a user, adding a custom theme to a UI library or typing extra environment variables. Interviewers want to hear that augmentations must live in a file that is a module and be included in the compilation, otherwise they silently do nothing.
Q23.How do function overloads work, and when would you use a generic or a union instead?
Overloads declare several call signatures followed by one implementation signature that is not visible to callers. They are useful when the return type depends on argument types in a way a single signature cannot express, such as returning an element for a string selector and an array for a list flag.
In many cases a generic or a union parameter is simpler and easier to maintain. Overload order matters because the compiler picks the first matching signature, and the implementation is checked loosely, so mistakes there are easy to miss.
Q24.What is the difference between `import type` and a regular import, and why does `verbatimModuleSyntax` matter?
import type is guaranteed to be erased, so it never creates a runtime dependency or a circular import at runtime. With verbatimModuleSyntax, TypeScript stops guessing which imports are type-only: anything without the type modifier is kept in the output exactly as written.
This matters because tools that compile one file at a time, such as esbuild, SWC and Node type stripping, cannot see other files to decide what is a type. Explicit import type makes every file safe to transform in isolation.
TypeScript Interview Questions for Experienced (3+ Years)
11 questions
Q25.How do mapped types work? Build a type that makes selected keys optional.
A mapped type iterates over keys with [K in keyof T] and transforms each property. Modifiers readonly and ? can be added or removed with + and -, and key remapping with as lets you rename or filter keys, such as producing getter names or dropping function members.
Strong candidates compose mapped types with built-ins rather than writing one giant type, and they know mapped types over keyof T are homomorphic, so they preserve the original optional and readonly modifiers.
type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
}Q26.Explain conditional types and distribution over unions.
A conditional type T extends U ? X : Y picks a branch based on assignability. When T is a naked type parameter and receives a union, the condition is applied to each member separately and the results are unioned. That is how Exclude and Extract work.
Sometimes distribution is unwanted, for example checking whether a whole type is never. Wrapping both sides in a tuple, [T] extends [U], switches it off. Candidates who can explain why IsNever<never> returns never without that wrapper usually understand conditional types properly.
Q27.How does the `infer` keyword work? Show an example beyond the built-in utilities.
infer declares a type variable inside the extends clause of a conditional type, letting the compiler capture part of a matched type. ReturnType is built this way. You can also add a constraint, as in infer N extends number, to filter what is captured.
Real uses include extracting the element type of an array, the payload type from an action creator or the route params from a path string. Interviewers want restraint: if a type needs several nested infer steps, document it or simplify the API.
type ElementOf<T> = T extends readonly (infer E)[] ? E : never
type Unwrap<T> = T extends { data: infer D } ? D : never
type A = ElementOf<string[]> // string
type B = Unwrap<{ data: { id: number } }> // { id: number }Q28.What are template literal types, and where are they useful in real code?
Template literal types build string types from other types, using the same syntax as JavaScript template strings, and they distribute over unions. Combined with intrinsics such as Uppercase and Capitalize, they can generate event names like onClick from click, CSS variable names or typed translation keys.
With infer they can parse strings, for example extracting :id parameters from a route path. The trade-off is performance and readability: large unions multiply quickly, and very clever string parsing types can noticeably slow the editor.
Q29.How do you use branded types to prevent mixing up IDs and units?
Because typing is structural, UserId and CourseId declared as string are interchangeable. A brand intersects the base type with a unique phantom property, such as string & { readonly __brand: "UserId" }, so the two are no longer assignable to each other while staying plain strings at runtime.
Values are created only through a constructor function that validates input, often a Zod schema with .brand(). This works well for IDs, money in paise versus rupees and sanitised HTML. Overusing brands for every string creates friction without benefit.
type Brand<T, B extends string> = T & { readonly __brand: B }
type UserId = Brand<string, 'UserId'>
type CourseId = Brand<string, 'CourseId'>
const toUserId = (raw: string): UserId => raw as UserId
function enrol(user: UserId, course: CourseId) {}
// enrol(courseId, userId) -> compile errorQ30.Explain variance in TypeScript. Why are method parameters treated differently from function properties?
Covariance means a subtype can stand in for a supertype, as with return types. Contravariance flips it, which is correct for function parameters: a handler for Animal can replace a handler for Dog, but not the reverse. With strictFunctionTypes, properties declared as function types are checked contravariantly.
Methods declared with method syntax remain bivariant for compatibility with patterns like DOM event handlers and arrays, which is a known unsoundness. Optional in and out annotations on type parameters document intended variance and can speed up checking.
Q31.Why do we need runtime validation such as Zod if we already have TypeScript?
Types are erased, so anything crossing a trust boundary, such as HTTP request bodies, third-party API responses, environment variables, local storage and message queues, arrives untyped. Casting with as just lies to the compiler.
A schema library like Zod validates at runtime and lets you derive the static type with z.infer, so schema and type cannot drift. Strong answers mention validating at the edges once and trusting types internally, returning clear errors with safeParse, and that Standard Schema lets libraries accept Zod, Valibot or ArkType interchangeably.
import { z } from 'zod'
const Enquiry = z.object({
name: z.string().min(2),
phone: z.string().regex(/^[6-9]\d{9}$/),
course: z.enum(['playwright', 'full-stack']),
})
type Enquiry = z.infer<typeof Enquiry>
const result = Enquiry.safeParse(await req.json())Q32.How do project references and incremental builds improve TypeScript performance in a monorepo?
Project references split a repo into smaller projects, each with composite: true, that depend on each other through references. tsc -b builds them in dependency order and skips projects whose inputs have not changed, using .tsbuildinfo files. Each project only reads the declaration output of its dependencies rather than rechecking their sources.
Experienced candidates also mention measuring with --extendedDiagnostics and --generateTrace, using skipLibCheck, adding explicit return types to exported functions, and simplifying very large unions or deeply recursive types that dominate check time.
Q33.What is Node type stripping, and what are its limitations?
Recent Node versions can run .ts files directly by erasing type annotations and replacing them with whitespace, without a separate build step. In current LTS releases this is on by default. It does not type-check and does not read tsconfig.json, so you still run tsc --noEmit in CI.
It only supports erasable syntax: enums, namespaces with runtime code and constructor parameter properties need transformation and fail. Imports need explicit .ts extensions and type-only imports must use import type. It suits scripts, tools and services; libraries still publish compiled JavaScript.
Q34.What does the `erasableSyntaxOnly` flag do, and why would a team turn it on?
erasableSyntaxOnly makes the compiler error on TypeScript features that generate runtime code: enum, namespaces containing values, constructor parameter properties and import aliases using import x = require(). Everything left can be removed by deleting type annotations.
Teams enable it when code runs through Node type stripping or other strip-only tools, so problems surface in the editor rather than as a runtime syntax error. It also aligns with the TC39 type annotations direction. Migration usually means replacing enums with as const objects and writing out constructor assignments.
Q35.What do you know about the native Go-based TypeScript compiler, TypeScript 7 or `tsgo`?
The TypeScript team is porting the compiler and language service to Go to get native speed and shared-memory parallelism. Preview builds expose a tsgo command, and published benchmarks show large codebases type-checking roughly an order of magnitude faster, with lower editor memory use.
The type system semantics are meant to stay the same, but deprecated options are removed and tools relying on the JavaScript compiler API need updated integration. A good answer stays conceptual: try it in CI alongside tsc, compare diagnostics, and plan migration rather than switching blindly.
TypeScript Scenario-Based Interview Questions
8 questions
Q36.An API response typed as `User` crashes in production because a field is missing. How do you fix it properly?
First confirm the cause: the type was asserted, likely via as User or an untyped fetch().json(), so the compiler never saw the real payload. Patching with optional chaining at the crash site only hides it.
The proper fix is a schema at the boundary: parse the response with Zod, decide whether a missing field is an error or should get a default, log validation failures with enough context, and derive the User type from the schema. Then search the codebase for other as casts on external data.
Q37.You join a project with 2,000 uses of `any` and `strict` disabled. How do you migrate it?
Do not flip strict on globally and drown the team in thousands of errors. Enable flags one at a time, starting with noImplicitAny and strictNullChecks, and scope them using a stricter tsconfig for new folders or a tool that tracks errors per file so the count can only go down.
Add a lint rule banning new explicit any, and fix types at sources such as API clients and shared models first, since that removes the most any downstream. Track progress weekly and pair migration with feature work.
Q38.Type checking in CI now takes eight minutes and the editor lags. How do you investigate?
Measure before guessing. Run tsc --extendedDiagnostics to see check time, file count and memory, then --generateTrace and analyse the trace to find the files and types that dominate. Often it is one huge union, a recursive conditional type or an accidental include of generated or build output.
Fixes include tightening include and exclude, enabling skipLibCheck and incremental, splitting into project references, and adding explicit return types to heavy exports. Trialling tsgo in CI is reasonable, but fix the pathological types first.
Q39.Your Node service compiles cleanly but fails at runtime with module not found errors. What happened?
Usually the tsconfig does not match how Node runs the code. A common cause is moduleResolution set to bundler for a service Node runs directly, allowing extensionless relative imports that Node ESM rejects. Path aliases from paths are another culprit, since TypeScript does not rewrite them.
Fix it by switching to module and moduleResolution nodenext, adding proper extensions, and replacing paths with package.json imports subpath patterns or a workspace package. Then add a smoke test that actually starts the built service in CI.
Q40.A teammate added a new order status and three screens silently showed blank labels. How would you prevent this class of bug?
The status was probably a plain string or a union handled with if chains and object lookups typed loosely, so nothing forced each screen to handle the new value.
Model status as a literal union or discriminated union from one source, use switch statements with a never exhaustiveness check, and type label maps as Record<OrderStatus, string> so a missing key is a compile error. Then add a lint rule that flags non-exhaustive switches, and a unit test that renders every status.
Q41.You must share types between a Next.js frontend and a Node backend in a monorepo. How do you set it up?
Create a shared workspace package that owns the contracts, ideally Zod schemas with inferred types, so both sides validate and type from the same source. Give it a proper package.json with exports, and either build it with declarations or consume source directly where both toolchains support it.
Watch the boundaries: the shared package must not import server-only code such as database clients into the frontend bundle. Use project references or workspace build tasks so changes to the contract rebuild and type-check dependent apps in CI.
Q42.The team wants to drop the build step and run TypeScript directly with Node type stripping. What do you check first?
Check for non-erasable syntax: enums, namespaces with values, parameter properties and decorators that need transformation. Turn on erasableSyntaxOnly and verbatimModuleSyntax to find them, and ensure relative imports use .ts extensions with rewriteRelativeImportExtensions if you still emit for some targets.
Then confirm the production Node version supports it without flags, keep tsc --noEmit as a CI gate since Node will not type-check, and consider whether dependencies or published packages still need compiled JavaScript. Roll out to internal scripts before the main service.
Q43.A generic helper you wrote infers `unknown` or overly wide types at call sites. How do you debug and fix it?
Hover over the call to see what the compiler inferred for each type parameter, then reduce it to a minimal example in the TypeScript playground. Common causes are a type parameter that appears only in the return type, inference from a callback that has not been contextually typed yet, or a literal widening to string.
Fixes include reordering parameters so inference sources come first, using const type parameters to keep literals, using NoInfer to stop a parameter from influencing inference, or simply asking callers to pass the type argument explicitly.