TypeScript interviews should reveal whether a candidate can use static types to express real contracts while reasoning correctly about JavaScript execution. Recruiters need to assess narrowing, generics, external-data validation, asynchronous behavior, and the relationship between compiler configuration and the runtime. Knowing advanced syntax is less useful than recognizing which assumptions a successful type check does and does not establish.
This guide to 100+ TypeScript Interview Questions and Answers contains 120 questions across beginner, intermediate, and experienced levels. It moves from everyday types and functions to inference, conditional types, module resolution, package declarations, migration, and production diagnosis. The examples emphasize maintainable APIs and explicit boundaries between static checking and runtime evidence.
How can recruiters assess genuine TypeScript engineering judgment when interview assistance can conceal gaps in type-system limits and runtime validation?
Give candidates an unknown payload, a misleading assertion, or a package that checks locally but fails after deployment. Ask them to explain the unsupported assumption, propose a minimal correction, and distinguish compiler tests from runtime tests.
Sherlock AI helps hiring teams assess signals of potential AI cheating, deepfakes, impersonation, and unauthorized assistance during interviews.
Evaluate those signals alongside practical work and the candidateโs explanation, not as conclusive proof of misconduct. A useful TypeScript exercise rewards accurate contracts, clear reasoning, and verification appropriate to the actual toolchain.
TypeScript Interview Questions
The complete question bank appears first so interviewers can select prompts without revealing answers. State the compiler version, important options, runtime, and build tools when a scenario depends on them.
TypeScript Interview Questions for Beginners
Establish the language model, common types, narrowing, functions, classes, and configuration. Look for clear distinctions between static descriptions and runtime values.
What is TypeScript?
How does TypeScript differ from JavaScript at runtime?
What does the TypeScript compiler do?
What is type inference?
When should you write an explicit type annotation?
What are the main primitive types in TypeScript?
How do any and unknown differ?
What does never represent?
How does void differ from undefined?
How do null and undefined behave with strictNullChecks?
What is a union type?
What is an intersection type?
What are literal types?
What is type narrowing?
How does a typeof check help with narrowing?
What is a discriminated union?
How do interface and type aliases differ?
What is structural typing?
What does an optional property mean?
What does readonly guarantee?
How do arrays and tuples differ?
What are generics useful for?
What is a generic constraint?
What does keyof produce?
What is an indexed access type?
What is a type assertion?
What does the non-null assertion operator do?
How do optional chaining and nullish coalescing differ?
How do you type a function's parameters and return value?
How do optional parameters differ from parameters accepting undefined?
What are function overloads?
What is a class in TypeScript?
How do implements and extends differ?
How do TypeScript private members differ from JavaScript private fields?
What does an async function return?
What is a module in TypeScript?
What is a declaration file?
What is tsconfig.json used for?
What does strict mode enable?
Why are runtime tests still needed in TypeScript?
TypeScript Interview Questions for Intermediate
Explore inference, generic relationships, advanced type operations, callback behavior, module settings, and public declarations. Ask candidates to explain the assumptions behind each technique.
How would you validate unknown JSON before using it as a domain object?
How do user-defined type guards work?
How does an assertion function differ from a type assertion?
How would you make discriminated-union handling exhaustive?
Why can truthiness narrowing cause bugs?
How would you model success and failure without unrelated optional fields?
How does exactOptionalPropertyTypes change assignment semantics?
What does noUncheckedIndexedAccess help detect?
How do excess-property checks differ from exact object types?
What does the satisfies operator do?
What does an as const assertion do?
How would you write a generic property-access function?
Why can a generic function not return any value satisfying its constraint?
How do generic defaults and inference interact?
What are mapped types?
How do Partial, Required, Pick, and Omit differ?
What is a conditional type?
When do conditional types distribute over unions?
What does infer do in a conditional type?
What are template literal types useful for?
How would you model identifiers that share the same primitive representation?
How do readonly arrays improve API design?
What is variance in a generic type?
How does strictFunctionTypes affect callbacks?
Why can a function returning a promise fit a void callback type?
How do overload signatures differ from a union-parameter implementation?
How does contextual typing affect callback inference?
How should caught errors be handled under strict checking?
How would you type a promise-based API response?
What is the difference between target and lib in tsconfig?
How do module and moduleResolution differ?
Why does a paths alias not automatically work at runtime?
What are type-only imports useful for?
What does isolatedModules help detect?
How would you diagnose editor and CI type-check differences?
What does skipLibCheck trade off?
How would you publish types for a JavaScript package?
Why can enum behavior surprise a JavaScript consumer?
How would you migrate JavaScript to TypeScript incrementally?
How would you review a TypeScript API for usability?
TypeScript Interview Questions for Experienced
Use these scenarios to assess boundary validation, mutation hazards, packaging, compatibility, performance, migration, and assurance. Strong answers balance precision with maintainability and honest limits.
How would you investigate a runtime failure in code that passes type checking?
How would you design a trustworthy parser returning a domain type?
How would you prevent types from drifting away from runtime validation?
How would you use branded types without creating false confidence?
How would you model a state machine with TypeScript?
How can mutation invalidate assumptions after narrowing?
How would you reason about asynchronous gaps and mutable state?
How would you handle array covariance and mutation hazards?
How would you design a generic API that preserves useful inference?
How would you diagnose a conditional type that unexpectedly becomes never?
How would you control complexity in recursive type utilities?
How would you distinguish TypeScript checking performance from runtime performance?
How would you investigate a slow TypeScript build?
How do project references help larger codebases?
How would you diagnose a package that compiles locally but fails for consumers?
How would you support both ESM and CommonJS consumers?
Why can esModuleInterop fail to solve a runtime interop problem?
How would you manage type-only dependencies in a library?
How would you evaluate a breaking change to a public type?
How would you test expected type errors?
How should ts-ignore and ts-expect-error be used?
How would you adopt stricter compiler options in an established project?
How would you evaluate a TypeScript compiler upgrade?
How would you distinguish transpilation from type checking in a build pipeline?
How would you model cancellation in an asynchronous API?
How would you type an event system without accepting every string and payload?
How would you model a patch request safely?
Why is Omit not a safe way to remove secrets from an object?
How would you keep domain validation separate from authorization?
How would you handle inaccurate third-party declarations?
How would you use module augmentation responsibly?
How would you reason about decorators across TypeScript configurations?
How would you avoid accidental global declarations?
How would you investigate duplicate type identities from dependencies?
How would you design types for serialized data?
How would you decide whether an advanced type utility is worth keeping?
How would you review a type guard during a security-sensitive code review?
How would you design a practical TypeScript interview exercise?
What evidence would you collect before declaring a TypeScript migration successful?
What does strong TypeScript engineering look like in practice?
TypeScript Interview Questions and Answers
The answers follow the exact wording, numbering, and order of the bank. Examples assume modern TypeScript with strict checking where relevant; specific feature and option dependencies are identified. No TypeScript compiler was available in the working environment, so every TypeScript example and expected diagnostic received static review only. Separately written JavaScript counterparts for selected runtime behaviors were exercised with Node.js 20.20.2. Those checks are not compilation, inference, or TypeScript compatibility tests. The cited 6.0 release notes are a versioned upgrade reference, not a claim that every project uses that version.
TypeScript Interview Questions and Answers for Beginners
Establish the language model, common types, narrowing, functions, classes, and configuration. Look for clear distinctions between static descriptions and runtime values.
1. What is TypeScript?
TypeScript adds a static type system and related language features to JavaScript, helping developers describe contracts and detect certain mistakes before execution. A function expecting a number can be checked against a call that supplies a string. The resulting program still follows JavaScript runtime behavior, and type checking does not prove the absence of bugs. Configuration, declarations, assertions, and untyped boundaries influence how much the compiler can establish. Use it alongside runtime validation and tests rather than as their replacement.
2. How does TypeScript differ from JavaScript at runtime?
Most TypeScript type syntax is removed during transformation and does not create runtime checks. JavaScript values and operations still determine execution. A declared response type does not validate a server's JSON payload. Some TypeScript constructs, such as ordinary enums, can produce runtime code, so 'all TypeScript disappears' is too broad. Inspect the chosen compiler or transpiler output and target environment. A successful type check describes the program under its declared assumptions, not the truth of every external value.
3. What does the TypeScript compiler do?
The compiler can parse source, analyze types, report diagnostics, and emit JavaScript and declaration-related artifacts according to configuration. These responsibilities are distinct: a pipeline may use TypeScript only for checking while another tool emits code. Emission behavior on errors depends on options and the command being used. Understand the actual build path before assuming a green bundle means type checking passed. The compiler also relies on library declarations that describe runtime APIs without installing those APIs.
4. What is type inference?
Type inference determines types from expressions and context when explicit annotations are absent. For example, initializing a variable with a number usually gives it a numeric type without a separate annotation. Inference reduces repetition, but it may widen literals or infer a broader result than an API designer intends. Inspect inferred public signatures and add annotations where they clarify a contract. Avoid annotating every local variable merely for appearance, and avoid assuming inference can discover facts hidden in unvalidated runtime data.
5. When should you write an explicit type annotation?
Use annotations where they define an important boundary, clarify intent, or prevent an inferred public contract from changing accidentally. Function parameters and exported return types often benefit, while simple local initializers may already be clear. An annotation should express the intended domain rather than suppress a mismatch. If a value does not satisfy it, investigate the data or design. More annotations do not automatically mean greater safety, especially when they rely on assertions or permissive types that bypass useful checks.
6. What are the main primitive types in TypeScript?
Common primitive types include string, number, boolean, bigint, symbol, null, and undefined, corresponding to JavaScript value categories. Use lowercase primitive type names rather than wrapper types such as String for ordinary values. The number type does not distinguish integers, finite numbers, or safe integers by itself, so domain constraints need runtime checks or validated abstractions. BigInt availability also depends on the target runtime and compilation settings. A type name describes a category, not every business invariant within it.
7. How do any and unknown differ?
The any type largely opts out of checking for operations on a value and can propagate that loss of safety. Unknown can hold an arbitrary value, but operations require narrowing or another justified refinement first. It is often a better starting point for external data. Neither validates the value automatically. If JSON is assigned to unknown, the application still needs to inspect its structure before using it as a domain object. Reserve any for deliberate, contained interoperability boundaries rather than routine convenience.
8. What does never represent?
Never represents a type with no possible values, often arising from unreachable branches or functions that cannot return normally. It is useful for exhaustive handling of discriminated unions: after all variants are handled, the remaining value should be never. This is a compile-time property under the declared types. A bad assertion or unvalidated external value can still violate those assumptions at runtime, so an unreachable-case helper may also throw defensively rather than silently return an invented result.
9. How does void differ from undefined?
Void commonly describes a function result that callers should not use, while undefined is an actual JavaScript value and a narrower type. TypeScript has special compatibility rules for void-returning callbacks: a function returning a value can often be supplied where its result will be ignored. That does not mean every function explicitly annotated void may return an arbitrary value. Understand the context before drawing conclusions. The distinction is particularly relevant when callback APIs discard results, including accidentally discarded promises.
10. How do null and undefined behave with strictNullChecks?
With strictNullChecks enabled, null and undefined are distinct types that cannot generally be used where a concrete value is required without handling their possibility. This catches operations such as calling a method on a potentially absent result. Without the option, many such mistakes are harder to detect statically. The setting does not remove nullish values from runtime inputs. Use explicit checks, defaults, or domain modeling appropriate to the task instead of adding assertions simply to silence diagnostics.
11. What is a union type?
A union represents a value that may belong to one of several types, such as string or number. Code can use operations valid for the current narrowed possibilities, not automatically every operation from every member. A status can be modeled as a union of specific strings rather than an unrestricted string. Unions describe alternatives; they do not merge all properties into one guaranteed object. Good handling usually narrows through observable runtime information before performing member-specific work.
12. What is an intersection type?
An intersection combines requirements from multiple types, so a value must satisfy each constituent. It is useful for composing object capabilities, but conflicting properties can produce impossible requirements rather than a convenient override. Intersecting an object with a string-valued id and one with a number-valued id does not choose one definition. Inspect the resulting type and the intended domain. Intersections are type-level composition; they do not create or merge runtime objects by themselves.
13. What are literal types?
Literal types describe specific values, such as the string 'ready' or the number 200, rather than every value in a primitive category. They support constrained states and discriminated unions. Inference may preserve or widen a literal depending on mutability and context, so an object property initialized with 'ready' is not always inferred as that exact literal. Use appropriate annotations or const assertions when exactness is intended. Literal types still do not validate arbitrary strings received from an external system.
14. What is type narrowing?
Narrowing refines the compiler's view of a value based on control flow and checks such as typeof, equality, property presence, or a discriminant. A value that begins as string or number can be treated as a string inside a verified string branch. The check must match the property being relied on. Truthiness can unintentionally exclude valid empty strings or zero. Narrowing is most useful when the runtime condition and intended domain distinction are clearly aligned.
15. How does a typeof check help with narrowing?
A typeof check can distinguish JavaScript primitive categories and functions, allowing TypeScript to refine a union accordingly. It has JavaScript's limitations: typeof null is 'object', and arrays also produce 'object'. Therefore, checking only typeof value === 'object' is insufficient for safely reading arbitrary object properties. Combine it with a null check and the necessary structural validation. The operator's runtime behavior should drive the guard, rather than assuming its English label precisely matches a domain type.
16. What is a discriminated union?
A discriminated union uses a shared property with distinct literal values to identify alternative object shapes. A result might have kind 'success' with data or kind 'failure' with an error. Checking kind lets the compiler associate the appropriate fields with each branch. This avoids combinations such as a success state with no data that a collection of unrelated optional properties can permit. The discriminant must still be validated when the value comes from an untrusted runtime boundary.
17. How do interface and type aliases differ?
Both can describe object shapes, but type aliases can also name unions, intersections, primitives, and other type expressions. Interfaces support declaration merging and can express extensible object contracts. The best choice depends on the public design rather than a universal rule that one is safer or faster. Unexpected merging can be undesirable for a closed internal shape, while intentional augmentation can be valuable for libraries. Neither creates a runtime object or validates an incoming value.
18. What is structural typing?
Structural typing compares relevant members rather than requiring an explicit declaration that one type implements another. An object with the required name property may satisfy a named interface even if it was created elsewhere. Extra-property checks for fresh object literals add useful diagnostics but do not make every object type exact. Class private and protected members introduce additional compatibility considerations. This flexibility supports JavaScript patterns, but distinct domain concepts with identical shapes may need additional modeling to prevent accidental interchange.
19. What does an optional property mean?
An optional property may be absent from an object, and reading it generally requires accounting for undefined. Absence and an explicitly present undefined value can have different runtime effects, such as property enumeration or the in operator. The exactOptionalPropertyTypes option makes assignment distinctions more precise unless undefined is explicitly included. Choose semantics that match the API, especially for patch operations where missing can mean unchanged and a present value can mean an update.
20. What does readonly guarantee?
Readonly restricts assignment through the type view where it appears. It does not generally freeze the runtime object or recursively make every nested value immutable. Another alias may still mutate shared data, depending on the design. A readonly array prevents mutating operations through that reference but can contain mutable objects. Use it to communicate and enforce intended access patterns during checking, and use appropriate runtime techniques or ownership discipline when actual immutability is required.
21. How do arrays and tuples differ?
An array describes a sequence whose elements follow a type, while a tuple can describe positions with distinct types and a known structure. A coordinate pair can be modeled as two numbers, while a list of coordinates needs an array. Optional and rest tuple elements support more flexible shapes. These are static descriptions, not runtime length validation. External arrays still need checks, and operations that change length can complicate assumptions if mutable tuples are exposed carelessly.
22. What are generics useful for?
Generics express relationships between types across a reusable function or structure. An identity function can return the same type it receives without discarding information into any. The type parameter should carry meaningful information between positions rather than merely decorate the signature. A generic function cannot assume arbitrary properties of an unconstrained type. Good generic design preserves useful specificity while keeping the API understandable and compatible with the runtime operation it actually performs.
23. What is a generic constraint?
A constraint states the minimum type requirements a type parameter must satisfy, allowing the implementation to use those features. For example, a function that reads length can constrain its input to a shape containing a numeric length property. It still cannot return an arbitrary object with length and claim it is every possible subtype of the caller's input. The constraint describes available capabilities; it does not erase additional caller-specific requirements or validate external data at runtime.
24. What does keyof produce?
Keyof produces a type representing the keys available on another type, often a union of property names. Index signatures and numeric keys can make the result broader than a simple list of string literals. It is useful for relating a selected key to an object's value type. It does not enumerate an object's runtime keys. Keep the distinction clear when working with Object.keys, which observes actual enumerable properties and may include data beyond the declared shape.
25. What is an indexed access type?
An indexed access type selects the type of a property or group of properties from another type, such as T[K]. Combined with a constrained key, it can preserve the relationship between a requested field and its return value. This avoids manually repeating property types that can drift apart. It is a type-level operation, not an actual property read. Runtime code still needs a valid object and key, especially when either comes from untrusted or dynamically validated input.
26. What is a type assertion?
A type assertion tells the compiler to treat a value as a specified type within the allowed assertion rules. It does not convert the value or validate its shape at runtime. Asserting that parsed JSON is a User can hide missing fields until execution fails. Prefer narrowing or validation when facts are uncertain, and use assertions only when a justified invariant cannot be expressed conveniently. Double assertions can bypass useful checks and should receive particular scrutiny.
27. What does the non-null assertion operator do?
The postfix non-null assertion removes null and undefined from the compiler's view of an expression. It does not check the value at runtime. It can be reasonable when an invariant is established elsewhere, but repeated use often conceals a missing lifecycle or data check. For example, asserting that a DOM lookup succeeded can still lead to a runtime error if the element is absent. Prefer an explicit check when absence is a legitimate possibility that the program must handle.
28. How do optional chaining and nullish coalescing differ?
Optional chaining stops a property access or call when the relevant receiver is null or undefined. Nullish coalescing supplies a fallback only for null or undefined, preserving values such as zero, false, and an empty string. They solve related but different problems. Neither validates arbitrary object structure, and a fallback should match the domain rather than hide unexpected missing data. The logical OR operator has broader falsy behavior, which can be incorrect when zero is a meaningful value.
29. How do you type a function's parameters and return value?
Describe the accepted inputs and resulting value, using inference for straightforward implementations and explicit annotations where a public contract matters. Account for optional or rest parameters and asynchronous results. A signature should reflect what callers may legitimately provide, not only the current call site. Avoid annotating a return type so broadly that it loses a useful relationship to the inputs. Function types guide checking, while JavaScript execution still determines argument handling and runtime behavior.
30. How do optional parameters differ from parameters accepting undefined?
An optional parameter permits omission at the call site and is treated as potentially undefined inside the function. A required parameter whose type includes undefined still represents a required argument position, even though undefined is an allowed value. Defaults introduce additional call and implementation semantics. Choose the form that communicates the intended API, especially for callbacks. Marking a callback parameter optional means the caller of that callback may omit it; it does not simply let implementers ignore a required argument.
31. What are function overloads?
Overloads describe multiple permitted call signatures for one implementation. They are useful when input forms have distinct relationships to output types that a simple union does not express clearly. The implementation signature is not an extra public overload for callers. Its body must correctly handle the supported cases at runtime. Prefer a union parameter when it describes the behavior adequately, because unnecessary overloads can make inference and maintenance harder without improving the actual contract.
32. What is a class in TypeScript?
A class defines a JavaScript runtime construct with additional static checks for fields, methods, inheritance, and access-related declarations. It can be used as both a value, such as a constructor, and a type describing instances. An interface only describes a type-level contract. Class declarations do not automatically validate constructor inputs or external objects. Consider initialization order, target-specific emit, and actual runtime methods when reasoning about behavior rather than treating a class as a purely static record.
33. How do implements and extends differ?
Implements checks that a class's instance shape satisfies an interface or other appropriate contract; it does not copy methods or provide runtime behavior. Extends creates an inheritance relationship and carries JavaScript runtime semantics. An implements clause also does not automatically infer every method parameter type from the interface. Use inheritance when the behavioral relationship is justified and composition when it is clearer. Both choices still require testing the actual implementation, not only satisfying a structural type check.
34. How do TypeScript private members differ from JavaScript private fields?
TypeScript's private modifier primarily enforces access restrictions during type checking, while JavaScript #private fields have runtime privacy semantics. Their behavior and emitted representation depend on the target and tooling. Neither is a substitute for securing sensitive data across an application's trust boundary. A value stored in an object can still affect observable behavior or be exposed by its methods. Choose the feature for its language semantics and compatibility requirements rather than assume a private keyword encrypts or protects secrets.
35. What does an async function return?
An async function returns a promise, with its declared return type typically expressed as Promise<T>. Returning a plain value from the body fulfills the promise with that value, while throwing rejects it. TypeScript can check value types but does not ensure callers await or handle every rejection. A promise-returning callback passed to an API that ignores return values can create operational problems. Understand the receiving API's runtime behavior and use appropriate linting and tests for asynchronous control flow.
36. What is a module in TypeScript?
A module organizes exported and imported code under the module system used by the runtime or bundler. TypeScript checks and may transform module syntax according to configuration, but the host ultimately resolves and loads the emitted program. A file's interpretation can depend on imports, exports, package metadata, and compiler settings. Do not assume every module-looking source runs unchanged in every environment. Align the type checker, emitter, package configuration, and execution host.
37. What is a declaration file?
A declaration file describes the types of JavaScript APIs without normally supplying their runtime implementation. It can explain library exports, globals, and callable shapes to the checker. A correct-looking declaration does not prove that the installed runtime library matches it. Version mismatches or inaccurate declarations can produce programs that compile and fail when executed. Review the relationship between declarations and actual package exports, and test public APIs rather than treating type availability as evidence that an implementation exists.
38. What is tsconfig.json used for?
Tsconfig.json identifies a TypeScript project and configures source inclusion, checking, module behavior, emit, and related options. The effective settings can come from inherited configurations and command-line overrides. Understand which project file the editor and build actually use before diagnosing differences. Passing source filenames directly to certain compiler invocations can change how project configuration is applied. A configuration file is not automatically authoritative for every transpiler or runtime in the toolchain.
39. What does strict mode enable?
The strict option enables a family of stricter checking options, whose composition can evolve with compiler versions. It is a strong baseline but does not include every useful safety-related option or make the language fully sound. Options such as noUncheckedIndexedAccess and exactOptionalPropertyTypes need separate consideration. Check the effective configuration and relevant release notes. Enabling strict can reveal assumptions that deserve design fixes; replacing every diagnostic with any or an assertion defeats much of its purpose.
40. Why are runtime tests still needed in TypeScript?
Static checking cannot establish every algorithmic invariant, external data shape, authorization rule, or asynchronous outcome. A function can have the correct number return type and calculate the wrong tax. Assertions and declaration mismatches also create gaps between types and values. Use tests for behavior and runtime validation at untrusted boundaries, while type-level tests protect important API contracts. The two forms of evidence complement each other and should be reported separately rather than summarized as 'TypeScript guarantees it works.'
TypeScript Interview Questions and Answers for Intermediate
Explore inference, generic relationships, advanced type operations, callback behavior, module settings, and public declarations. Ask candidates to explain the assumptions behind each technique.
41. How would you validate unknown JSON before using it as a domain object?
Treat the parsed value as unknown and check the required structure and business constraints through a parser or validation library. Confirm that an object is non-null, fields have the expected types, and values satisfy relevant bounds. Return a validated domain value or a clear error rather than asserting success. Decide whether extra properties are accepted or rejected. A type predicate can communicate the result to the checker, but its implementation must actually establish every property it promises.
TypeScript runtime-parser example, statically reviewed.
This illustration accepts an object with the stated fields and returns a fresh object containing only id and age. It accepts extra input properties and does not establish identity, ownership, or a complete real-world age policy. It is intended for ordinary parsed data, not arbitrary hostile getters or proxies. Property narrowing uses modern TypeScript behavior, including unlisted-property narrowing available from 4.9. The TypeScript source was not compiled; only its separately written JavaScript counterpart was exercised.
42. How do user-defined type guards work?
A type guard can return a predicate such as value is User, allowing TypeScript to narrow a value when the function returns true. The compiler generally trusts that declared relationship; it does not prove the implementation checks every required field. A guard that only tests for an id property may be unsound for a richer User type. Keep guards small, test positive and negative runtime inputs, and review them as boundary code rather than treating the predicate annotation as validation itself.
43. How does an assertion function differ from a type assertion?
An assertion function has a signature describing a condition it establishes when it returns normally, and its body can perform runtime checks and throw on failure. A type assertion using as changes the compiler's view without executing validation. The assertion-function signature is still a promise the implementation must honor. Use it when failure should interrupt the current path and the validated condition is clear. A misleading assertion function can hide the same unsafe assumptions as a misleading cast.
44. How would you make discriminated-union handling exhaustive?
Handle each discriminant value and pass the remaining value to a helper accepting never, often with a defensive throw. Adding a new union member can then expose unhandled branches during checking. This works only within the declared type model; external data needs validation before it can be trusted as that union. Avoid a broad default that silently returns a fallback and conceals missing cases. Exhaustiveness is particularly useful for state transitions and result types with distinct required fields.
TypeScript exhaustive-union example, statically reviewed.
Adding another declared variant without handling it should make the never call invalid during type checking. That expected diagnostic was statically reviewed but not compiler-tested here. The defensive runtime throw was exercised only in a separate JavaScript analogue with synthetic inputs; external data still needs validation before it is treated as LoadResult.
45. Why can truthiness narrowing cause bugs?
Truthiness removes more than null and undefined: it also excludes values such as an empty string, zero, false, and NaN. A check intended to detect a missing numeric input can therefore reject a valid zero. Use explicit comparisons that match the domain, such as checking for undefined when absence is the concern. TypeScript can follow the control flow, but it cannot infer that the programmer intended a different business distinction. Tests should include meaningful falsy values.
46. How would you model success and failure without unrelated optional fields?
Use a discriminated union with one shape for success and another for failure, each carrying only the fields valid in that state. This makes impossible combinations harder to construct through checked code. For example, a successful response can require data while a failed response requires an error code. Keep runtime parsing aligned with the model. A broad object with optional data and optional error permits ambiguous states that every consumer must interpret, often inconsistently.
47. How does exactOptionalPropertyTypes change assignment semantics?
When enabled, it distinguishes an optional property's absence from a present undefined value unless undefined is explicitly included in the property type. Reading the property can still produce undefined because it may be absent. This is useful for patch objects and APIs where presence has meaning. Review object construction and spread behavior during adoption. The option improves the static model but does not alter JavaScript's runtime distinction or validate objects arriving from an unchecked boundary.
48. What does noUncheckedIndexedAccess help detect?
It adds undefined to certain indexed reads that are not known to exist, exposing assumptions about arrays and index signatures. Reading an arbitrary key from a dictionary should not automatically imply a value is present. The option can require checks or more precise modeling, such as a tuple for known positions. It is not a runtime bounds check. Use it to reveal uncertainty, then choose handling that reflects the domain rather than immediately applying non-null assertions to every lookup.
49. How do excess-property checks differ from exact object types?
TypeScript applies additional checks to fresh object literals in relevant assignment contexts, helping catch misspelled or unexpected properties. That does not mean a type prohibits every extra runtime property in all assignments. A value stored in another variable can be structurally compatible while carrying additional fields. If exactness matters at an API boundary, validate it explicitly. Do not use a successful assignment as evidence that an object contains only the declared keys, especially before serialization or access-control decisions.
50. What does the satisfies operator do?
Satisfies checks that an expression is compatible with a target type while preserving useful information about the expression instead of simply replacing its type with the target annotation. Contextual typing can still influence inference, so 'never changes inference' is too strong. It is useful for configuration objects where shape checking and specific property types both matter. It creates no runtime validation. The operator was introduced in TypeScript 4.9, so verify compiler support in projects using older toolchains.
TypeScript 4.9-or-later satisfies example, statically reviewed.
The target checks the key set and compatible values while the properties retain useful specific types for their operations. Satisfies is not a runtime validator. This example was not compiled or executed, and it does not claim exact inference is unchanged in every context.
51. What does an as const assertion do?
A const assertion preserves literal specificity and gives object properties or array literals readonly type treatment in the relevant expression. It is useful for deriving a union from a fixed set of values or keeping a discriminant narrow. It does not recursively freeze arbitrary referenced objects at runtime. A mutable object inserted into a const-asserted structure can still be changed through another reference. Use it to express static intent and distinguish that from actual immutability guarantees.
52. How would you write a generic property-access function?
Relate the key parameter to keyof T and the result to T[K], so selecting a known property preserves its corresponding value type. This is more informative than accepting any string and returning any. The runtime operation remains an ordinary property read, so inputs must satisfy the declared contract. For dynamic untrusted keys, validate membership or expose an appropriate optional result. A generic signature should capture a real relationship rather than promise that arbitrary runtime strings are valid keys.
TypeScript generic key/value relationship, statically reviewed.
The key constraint connects the selected property to its result type. This is for values already satisfying the declared contract, not validation of untrusted keys. The inferred results and expected invalid-key diagnostic were reviewed statically only.
53. Why can a generic function not return any value satisfying its constraint?
A constraint describes a minimum capability, while the caller's chosen type may contain additional properties or narrower values. If T extends an object with length, constructing a new object containing only length does not necessarily produce T. Returning it as T would discard caller-specific requirements. Design the function to return the constraint type, preserve the actual input, or accept a factory that can create the required subtype. Avoid assertions that conceal this mismatch between the generic promise and implementation.
54. How do generic defaults and inference interact?
A generic default supplies a type when the applicable type parameter is not otherwise specified or inferred under the declaration's rules. It is not a runtime default value. Defaults should satisfy constraints and produce a useful fallback API rather than hide missing relationships. Inspect real call sites because inference may choose a more specific or unexpected type. Adding a default can change the public experience of a generic library, so test compatibility instead of assuming it is merely documentation.
55. What are mapped types?
Mapped types construct a new type by transforming properties from a key set, often derived with keyof. They can add or remove optional and readonly modifiers or remap keys. This reduces duplicated declarations when the relationship is systematic. The result is purely a type description; no object transformation occurs at runtime. A mapped type can also become difficult to read if several transformations are nested, so give important intermediate concepts meaningful names and keep the public contract understandable.
56. How do Partial, Required, Pick, and Omit differ?
Partial makes properties optional, Required removes optional modifiers, Pick selects named properties, and Omit describes the remaining properties after excluding keys. These standard utility types are shallow transformations of the relevant type structure. Omit does not delete fields from a runtime object, and Partial does not validate a patch or define how undefined should be interpreted. Use them when their semantics match the domain, and add explicit runtime transformation or validation where the actual data must change.
57. What is a conditional type?
A conditional type selects a type based on an assignability relationship, often written with extends, a true branch, and a false branch. It can express relationships such as extracting an element type from an array-like type. This is evaluated by the type system, not as a runtime if statement. Complex conditions can produce surprising unions or never results, so test representative input types. Prefer a simpler direct type when the conditional machinery adds no meaningful relationship.
58. When do conditional types distribute over unions?
A conditional type commonly distributes when the checked type is a naked type parameter. Applying it to a union then evaluates members separately and combines the results. Wrapping the checked types in tuples can suppress that distribution when the whole union should be considered together. This distinction is useful for filtering unions but can also create unexpected results. Explain the intended transformation with a small example rather than relying on a memorized syntax trick without understanding its effect.
TypeScript conditional-type distribution example, statically reviewed.
The naked parameter in Distributed causes member-by-member distribution. Tuple wrapping in Whole tests the union as a whole. These are type-level results with no corresponding runtime branching, and no compiler was available to verify the expected types.
59. What does infer do in a conditional type?
Infer introduces a type variable for a position matched within the conditional's extends pattern. It can extract a function return type, array element, or another structural component. The result depends on the pattern and inference rules, including how multiple candidates interact. It does not inspect runtime values. Keep the extraction aligned with the supported input shapes and define a deliberate fallback for nonmatching types instead of allowing an unexpected never to propagate through a large public API.
60. What are template literal types useful for?
Template literal types construct string patterns from literal types and unions, enabling contracts such as a finite set of event names. They can relate a property name to an associated callback type when combined with other type operators. They do not parse or validate arbitrary runtime strings automatically. Large combinations can also increase type-checking work and become difficult to maintain. Use them for meaningful relationships with manageable scope rather than attempting to encode every possible string grammar in the type system.
61. How would you model identifiers that share the same primitive representation?
If user IDs and order IDs are both strings, ordinary structural typing may allow accidental interchange. A branded or opaque-style type can distinguish them statically, with controlled construction after validation. The brand usually has no inherent runtime enforcement unless the implementation adds it. Avoid scattering assertions that let any string become any identifier. The value of the pattern comes from disciplined boundaries and clear APIs, not from a special property name alone.
62. How do readonly arrays improve API design?
A readonly array parameter permits reading without allowing mutation through that reference, and it can accept both mutable and readonly arrays where compatible. This communicates that the function does not require ownership of the sequence. It does not make nested elements immutable or prevent mutation through other aliases. If the implementation needs to sort or modify elements, copy appropriately or document a different contract. The type should describe the function's real behavior rather than merely appease a caller's annotation.
63. What is variance in a generic type?
Variance describes how relationships between type arguments affect relationships between constructed types. A producer of values behaves differently from a consumer, and a type that both reads and writes can require stricter compatibility. TypeScript infers many relationships structurally and has deliberate exceptions for JavaScript compatibility. Explain the operations the API permits before assigning labels such as covariance or contravariance. Variance annotations, where supported, are not a general way to force incompatible structures to become safe.
64. How does strictFunctionTypes affect callbacks?
It makes parameter compatibility stricter for relevant function types, helping reject a callback that accepts a narrower input than the caller may supply. Method and constructor declarations have important exceptions, so the rule should not be described as universal contravariance for every callable member. A callback that only handles one subtype cannot safely process every value in a broader contract. Review the declaration form and compiler settings, and test the public API's intended assignability.
TypeScript strictFunctionTypes illustration, statically reviewed.
A caller allowed to provide any Animal could supply one without bark. The commented assignment states an expected negative type-check case rather than an executed compiler result. Method and constructor declaration exceptions are not illustrated by this function-expression example.
65. Why can a function returning a promise fit a void callback type?
TypeScript permits certain return values to be ignored when a function is assigned to a void-returning callback contract. That can include a promise, even if the receiving API does not await it or handle rejection. The assignment therefore does not prove safe asynchronous behavior. Inspect the API and use an explicit async-aware workflow or deliberate error handling. Lint rules can help detect these cases, but runtime tests are still needed for ordering and rejection behavior.
66. How do overload signatures differ from a union-parameter implementation?
Overloads can expose distinct input-output relationships to callers, while a union parameter gives one signature whose body narrows the alternatives. A call with a union-valued argument may not match separate overloads even when each concrete member would. The implementation signature must be compatible with the overloads but is not directly callable as an additional public option. Prefer the simpler union signature when it preserves the needed behavior, and use overloads when they provide meaningful precision.
67. How does contextual typing affect callback inference?
The surrounding expression can provide expected parameter or return types to a callback, allowing concise code without explicit annotations. An array's element type can inform a map callback, for example. Moving the callback into a separate unannotated variable may remove that context and change diagnostics or inference. Understand where the expected type originates before assuming two syntactically similar forms are equivalent. Contextual typing is useful, but an overly broad surrounding type can also hide information that callers need.
68. How should caught errors be handled under strict checking?
Treat a caught value as potentially arbitrary, often unknown under the relevant strict settings, because JavaScript permits throwing values other than Error objects. Narrow with suitable checks before reading message or other properties. An instanceof Error check is useful in many contexts but may have cross-realm considerations. Preserve useful error context without asserting every caught value has the desired shape. The error-handling policy should also distinguish recoverable failures from errors that must be propagated.
69. How would you type a promise-based API response?
Describe the fulfilled value with Promise<T>, but model application-level success and failure explicitly where the protocol requires it. The promise's type parameter does not describe every possible rejection value or validate a network payload. Parse external data before returning a trusted domain type. Separate transport failure, invalid data, and a legitimate business rejection so callers can handle them correctly. A generic fetch helper that simply casts JSON to T gives an appearance of safety without establishing the contract.
70. What is the difference between target and lib in tsconfig?
Target influences the JavaScript language level emitted by the compiler and related defaults, while lib selects declaration sets describing available APIs. Including a newer library declaration does not install or polyfill that API in the runtime. A project can therefore type-check a method that is unavailable where it executes. Choose both according to the real host and build pipeline, and test emitted code in supported environments. Syntax transformation and runtime API availability are separate compatibility concerns.
71. How do module and moduleResolution differ?
Module affects how TypeScript interprets and emits module-related code, while moduleResolution controls how it locates and interprets imports for checking. Their appropriate pairing depends on the host, such as Node or a bundler, and supported compiler modes. A configuration that finds declarations does not guarantee the runtime can load the same specifier. Use official host-oriented guidance and inspect emitted imports, package metadata, and resolution traces rather than changing options randomly until diagnostics disappear.
72. Why does a paths alias not automatically work at runtime?
Paths informs TypeScript's resolution of certain module specifiers; it does not generally rewrite emitted import strings to corresponding runtime paths. The bundler, loader, or runtime needs compatible resolution behavior, or the package design should use supported alternatives. A project can compile while failing with a module-not-found error after deployment. Verify the actual output and execution environment. Do not use an alias solely to silence a missing-module diagnostic without understanding how the referenced code will be loaded.
73. What are type-only imports useful for?
Type-only imports express that an import is needed for checking rather than runtime use, allowing tooling to erase it according to the relevant rules. They help clarify dependencies and avoid unintentionally requiring a runtime export that exists only as a type. If a module has required side effects, those need an appropriate value or side-effect import. Review settings such as verbatimModuleSyntax and the build tool's behavior rather than assume all import forms are interchangeable.
74. What does isolatedModules help detect?
It warns about constructs that cannot be handled safely by tools that transform files independently without full-program type information. This is relevant when a transpiler removes TypeScript syntax while a separate process performs checking. It does not itself turn that transpiler into a type checker or guarantee every build integration is correct. Keep a real type-checking step where required and verify supported syntax. The option describes a tooling constraint, not complete isolation of modules at runtime.
75. How would you diagnose editor and CI type-check differences?
Compare compiler versions, effective configuration, included files, dependency versions, generated declarations, and the exact commands used. The editor may use a bundled TypeScript version while CI uses a project dependency. Case-sensitive paths and platform differences can also matter. Reproduce the CI invocation locally where possible and inspect configuration rather than adding suppressions. A consistent lockfile and explicit toolchain selection help, but the diagnosis should establish the actual mismatch before changing application code.
76. What does skipLibCheck trade off?
SkipLibCheck skips checking declaration files themselves, which can reduce checking time or avoid dependency-declaration conflicts. It does not mean all uses of library types become unchecked, nor does it fix an incorrect public declaration. Errors can remain hidden in the declaration graph. Use it as a deliberate build trade-off and investigate incompatible dependencies when they affect the application. A clean build with the option enabled is weaker evidence about declaration consistency than a full check.
77. How would you publish types for a JavaScript package?
Ensure the declarations describe the actual exports, runtime behavior, and supported consumer module environments. Generate declarations when appropriate or maintain reviewed declaration files, then package them with correct metadata and export mappings. Test consumers rather than only the library's own source build. A declaration can compile internally while resolving incorrectly from an installed package. Version public type changes deliberately because consumers may depend on assignability and inference as well as runtime function names.
78. Why can enum behavior surprise a JavaScript consumer?
Ordinary TypeScript enums can emit runtime objects, and numeric enums have reverse-mapping behavior that differs from string enums. Const enums introduce separate inlining and distribution considerations. Consumers may observe those runtime details even if the author thinks only in terms of a type. For simple closed strings, a literal union or const object may be clearer. Choose deliberately based on interoperability and build constraints rather than assume every enum is erased or every enum form behaves the same.
79. How would you migrate JavaScript to TypeScript incrementally?
Establish the build and checking boundary, then add useful types around important interfaces and external data before pursuing maximum annotation coverage. Options such as allowJs and checkJs can support staged adoption, depending on the toolchain. Track unsafe assertions and any usage rather than hiding them as permanent progress. Introduce stricter checks in manageable steps with tests for existing behavior. Migration success means clearer contracts and fewer unsupported assumptions, not simply renaming every file to a TypeScript extension.
80. How would you review a TypeScript API for usability?
Try representative valid and invalid calls and inspect inference, error messages, and emitted declarations. The API should preserve meaningful relationships without requiring callers to provide unnecessary type arguments or assertions. Consider readonly inputs, optional-value semantics, and compatibility with common consumer settings. A sophisticated type expression is not automatically a good public interface. Favor contracts that are understandable, testable, and aligned with runtime behavior, and document the cases the type system intentionally cannot express.
TypeScript Interview Questions and Answers for Experienced
Use these scenarios to assess boundary validation, mutation hazards, packaging, compatibility, performance, migration, and assurance. Strong answers balance precision with maintainability and honest limits.
81. How would you investigate a runtime failure in code that passes type checking?
Compare the runtime value and execution path with the assumptions represented by the types. Look for unvalidated external data, assertions, any, inaccurate declarations, aliasing, and asynchronous state changes. A missing property may originate at a network boundary rather than where it is finally read. Reproduce the failure with a focused runtime test and strengthen the appropriate contract. Do not assume the compiler is defective simply because static checking did not establish an invariant it was never given enough information to prove.
82. How would you design a trustworthy parser returning a domain type?
Separate raw input from validated output and make success contingent on all required structural and business checks. Return a clear result or throw according to the API contract, preserving useful error details without exposing sensitive input. Decide normalization, unknown-field handling, and nested validation explicitly. The parser's return type is a promise about its implementation, so test malformed and boundary cases. Avoid validating a small subset of fields and then asserting the entire object satisfies a richer domain type.
83. How would you prevent types from drifting away from runtime validation?
Use a shared authoritative schema or carefully reviewed derivation where appropriate, and test that the runtime parser and exported type agree on representative cases. Generated types reduce duplication but do not eliminate errors in the schema or generator. Version changes together and review optionality, coercion, defaults, and extra-field behavior. A schema that converts values can produce an output type different from its input type. Keep that distinction explicit rather than assume one interface describes every stage of the boundary.
84. How would you use branded types without creating false confidence?
Restrict brand construction to validated or otherwise trusted functions and keep unsafe assertions visible and narrow. A branded string is still a string at runtime unless the implementation adds a representation. It cannot by itself prove database existence, ownership, or current authorization. Document exactly what the brand means, such as syntactic validation of an identifier. Use separate runtime checks for facts that can change. The pattern is valuable when it prevents accidental mixing, not when it disguises unchecked values.
85. How would you model a state machine with TypeScript?
Represent states and events with discriminated unions and define transitions that return only allowed next states under the intended contract. Keep state-specific data attached to the appropriate variant. Type checks can help reveal unhandled variants, but runtime events and persisted state still need validation. Some transition relationships may require explicit functions or runtime tables rather than one overly broad generic. Test invalid transitions and side effects separately, especially when external systems can change state between reads and writes.
86. How can mutation invalidate assumptions after narrowing?
Narrowing describes what the compiler can establish along a control-flow path, but aliases or callbacks can mutate shared data in ways the analysis may not fully model. A property checked before calling another function may change during that call. Reduce the risk through immutable data flow, local snapshots of relevant values, or explicit revalidation where needed. Do not generalize a successful narrowing into a guarantee about all future states of a shared object. Test the actual mutation boundary and ownership rules.
87. How would you reason about asynchronous gaps and mutable state?
An await allows other work to occur before the function resumes, so mutable external state may no longer match assumptions made earlier. Type annotations do not provide transaction isolation or prevent concurrent logical updates. Capture immutable inputs where appropriate and recheck current state before consequential operations. Define cancellation and stale-result handling. Even in a single-threaded JavaScript event loop, interleaved asynchronous operations can produce race conditions at the application level that static types alone do not solve.
88. How would you handle array covariance and mutation hazards?
Recognize that TypeScript permits some useful but potentially unsound assignments for JavaScript compatibility. Passing a mutable array of a narrower element type into a context that can insert broader values can undermine assumptions. Prefer readonly inputs when mutation is unnecessary, and design ownership boundaries deliberately. A compiler-accepted assignment is not a proof of complete soundness. Explain the operations that create the hazard and test the runtime behavior rather than rely only on abstract variance terminology.
89. How would you design a generic API that preserves useful inference?
Relate type parameters to actual input and output positions, avoid unnecessary constraints, and test the intended call patterns without explicit type arguments. Overly broad annotations or extra generic parameters can reduce useful inference. A parameter used only once may not express a meaningful relationship. Inspect emitted declarations and error messages from a consumer's perspective. Prefer a simpler signature when it conveys the same contract, and use overloads or conditional types only when they preserve information callers genuinely need.
90. How would you diagnose a conditional type that unexpectedly becomes never?
Reduce the type expression and evaluate representative members step by step, paying attention to distribution, constraints, and impossible intersections. Never can disappear from unions or arise because no branch matches the intended shape. Compare the result for a single concrete type and for the full union. Named intermediate aliases can make the behavior easier to inspect. Avoid adding an assertion at a call site before understanding whether the underlying type model incorrectly excludes valid values.
91. How would you control complexity in recursive type utilities?
Bound the problem and consider whether a simpler shallow contract or generated type would meet the need. Recursive mapped and conditional types can increase checking cost and produce difficult diagnostics, especially over large unions or deeply nested structures. Measure the actual compiler workload and test representative consumer types. Do not promise that an elegant recursive definition scales indefinitely. Public APIs should balance precision with understandable errors and practical compilation performance, including documented limits where appropriate.
92. How would you distinguish TypeScript checking performance from runtime performance?
Measure them separately. Complex type-level computations can slow the compiler or editor while disappearing from emitted JavaScript. Runtime performance depends on the executed code, data, environment, and transformations. Conversely, a simple type annotation can describe an expensive algorithm without changing its cost. Use compiler diagnostics or traces for checking problems and suitable runtime profiling for execution problems. Avoid claiming that replacing an interface with a type alias makes application code faster without evidence of a relevant runtime change.
93. How would you investigate a slow TypeScript build?
Establish which phase is slow and compare project size, dependency declarations, type complexity, configuration, and recent changes. Use supported compiler diagnostics or tracing rather than guess from file count. Repeated work across projects or pathological type instantiation may matter more than ordinary source length. Evaluate incremental builds or project references where appropriate, then measure the effect. Skipping checks can reduce time but changes assurance, so report that trade-off instead of presenting it as a free performance optimization.
94. How do project references help larger codebases?
Project references describe dependencies between TypeScript projects and can support organized builds with declaration boundaries and incremental behavior. They require appropriate configuration and a build process that respects the graph. They do not automatically solve runtime package resolution or make circular architectural dependencies harmless. Design project boundaries around meaningful ownership and dependencies, then verify clean and incremental builds. A monorepo can still expose inconsistent outputs if different tools ignore references or consume stale artifacts.
95. How would you diagnose a package that compiles locally but fails for consumers?
Test the installed package contents and metadata in representative consumer environments, not just source imports inside the repository. Check exported files, declarations, module format, dependency assumptions, and resolution conditions. Local aliases or workspace links can hide missing published artifacts. Reproduce the failure with a minimal consumer and inspect which declaration and runtime files are selected. A successful library build does not prove that the package's public distribution is complete or compatible with its advertised hosts.
96. How would you support both ESM and CommonJS consumers?
Treat the module formats as distinct runtime and packaging contracts, with appropriate exports, file extensions, and declarations for the supported environments. Verify actual import and require behavior under the chosen hosts and compiler modes. Interop helpers or synthetic default assumptions do not make every package combination equivalent. Test installed-package consumers and avoid exposing duplicate state unintentionally through separate builds. The right design depends on supported versions and tooling rather than a universal tsconfig recipe.
97. Why can esModuleInterop fail to solve a runtime interop problem?
The option affects TypeScript's checking and emitted interoperability behavior in relevant configurations, but it cannot rewrite every host's module semantics or repair incorrect package exports. A declaration may suggest a default import that the actual runtime does not provide in the expected way. Inspect emitted code, package type, module mode, and the execution environment. Interoperability is a relationship among several tools and formats, so changing one flag without testing the deployed path can leave the failure intact.
98. How would you manage type-only dependencies in a library?
Distinguish types required to describe the public API from implementation-only dependencies, and ensure consumers can resolve the declarations that reference them. Erasing a runtime import does not make its type dependency irrelevant to a published declaration file. Avoid leaking unnecessary internal types into exports. Inspect generated declarations and test a clean consumer installation. Dependency placement and packaging should reflect actual consumer needs rather than assume devDependencies are always sufficient for any package used only in source annotations.
99. How would you evaluate a breaking change to a public type?
Examine assignability, inference, optionality, overload selection, and supported compiler settings in representative consumer code. A runtime-compatible change can still break compilation or change inferred results. Adding a union member can intentionally surface missing exhaustive handling, while narrowing a parameter rejects previously accepted calls. Document the intended compatibility contract and use type-level tests when a compiler is available. Treat declarations as part of the public API rather than an incidental artifact that can change without review.
100. How would you test expected type errors?
Use a compiler-based fixture with a deliberate invalid call and an assertion mechanism such as a carefully placed ts-expect-error comment, then ensure the fixture fails if the expected diagnostic disappears. Also include positive cases so the API is not merely unusable. Be aware that the directive checks for an error on the relevant line, not necessarily a particular diagnostic message. Run against supported compiler versions when compatibility matters. Static reading of such a fixture is not equivalent to executing the compiler.
101. How should ts-ignore and ts-expect-error be used?
Both suppress relevant diagnostics, but ts-expect-error also reports when the anticipated error is no longer present, making it useful for negative type tests or tracked temporary workarounds. Keep suppressions narrow and explain the underlying issue. They do not change runtime behavior or establish that the code is safe. Prefer fixing the model or dependency where practical. An unexplained accumulation of suppressions can hide regressions and make a strict configuration appear stronger than the effective checks really are.
102. How would you adopt stricter compiler options in an established project?
Introduce options with a baseline and prioritize errors at important boundaries rather than mechanically asserting them away. Separate genuine bugs from declarations that need more precise modeling. Use staged changes and runtime tests to preserve behavior, and record any temporary exclusions with owners. Review inherited configuration and compiler-version differences. The objective is improved assurance and maintainability; a configuration that says strict while pervasive any and non-null assertions bypass its findings provides less benefit than the label suggests.
103. How would you evaluate a TypeScript compiler upgrade?
Read the relevant official release notes, pin the candidate version, and compare diagnostics, emit, declarations, and important consumer behavior using the project's real configuration. Defaults, deprecations, inference, and module behavior can change across versions. Separate necessary compatibility fixes from unrelated refactoring. Preserve a recovery path and test the actual build pipeline, including tools that embed their own compiler version. Do not describe a version as universally current or compatible merely because one local project builds successfully.
104. How would you distinguish transpilation from type checking in a build pipeline?
Identify which tool removes TypeScript syntax or transforms code and which tool analyzes the full type relationships. Some fast transpilers intentionally do not perform semantic type checking. A successful bundle therefore may coexist with type errors. Configure and run the checking step explicitly where required, and ensure CI treats its failures appropriately. Inspect source maps and emitted output separately. The pipeline should make each assurance claim clear instead of using the word compile for several different operations without distinction.
105. How would you model cancellation in an asynchronous API?
Define how callers request cancellation, how the operation observes it, and what result or error indicates cancellation under the runtime API. Types can describe accepted signals and results but cannot force an underlying operation to stop or undo completed side effects. Distinguish cancellation from timeout and failure, and test races around completion. A Promise<T> alone contains no cancellation guarantee. Document which work may continue and how callers should reconcile partial outcomes when the operation crosses external systems.
106. How would you type an event system without accepting every string and payload?
Relate event names to their payload types through a well-defined event map and generic keys, so a selected event determines the expected payload. Test listener and emitter signatures together, including invalid pairings. Runtime events from external sources still require validation. Avoid broad fallback overloads that unintentionally allow any event and defeat the typed contract. A useful design also considers listener removal, asynchronous callbacks, and error handling rather than focusing only on the generic signature.
107. How would you model a patch request safely?
Define whether omission means unchanged, whether null means clearing, and whether undefined is accepted or removed during serialization. Partial<T> alone does not answer these business questions or restrict which fields may be changed. Select allowed fields and validate the payload at the boundary, including authorization for sensitive updates. Consider exactOptionalPropertyTypes for clearer static semantics. Test missing, present-null, and present-value cases so the client and server agree on the operation rather than merely sharing a similar interface.
108. Why is Omit not a safe way to remove secrets from an object?
Omit changes the static type description; it does not delete properties from the runtime value. Passing an object through an Omit-based type can still leave secret fields present and serializable. Construct an explicit safe output object or perform a reviewed runtime transformation, then test its actual keys and serialized form. A type can help describe the intended response, but confidentiality depends on the data produced. Do not rely on the editor hiding a property as proof that it cannot be exposed.
TypeScript Omit versus runtime removal, statically reviewed.
The typed view refers to the original object; Omit does not remove its token property. Constructing a new output object performs the actual runtime selection. A separate JavaScript fixture checks both serialized key sets using a synthetic non-secret token. The TypeScript assignment itself remains statically reviewed only.
109. How would you keep domain validation separate from authorization?
Validation establishes that input has an acceptable structure and domain meaning, while authorization determines whether the current actor may perform the requested operation on the resource. A valid order ID or branded identifier does not prove ownership. Keep both checks explicit at the appropriate boundary and avoid encoding a transient permission as a permanent type fact. Types can organize the workflow, but permissions may change between validation and execution and require trusted runtime enforcement.
110. How would you handle inaccurate third-party declarations?
Confirm the mismatch with the installed library version and a minimal runtime or type-checking example. Prefer an upstream fix or supported version alignment, and use narrow local augmentation or a wrapper when necessary. Document the workaround and test the actual behavior it describes. Do not broaden an entire module to any simply to remove one diagnostic. Declaration changes can affect consumers beyond the immediate call site, so verify that the correction does not introduce a different unsupported promise.
111. How would you use module augmentation responsibly?
Augment only the module and declarations intended for extension, with a clear understanding of declaration merging rules and runtime support. Adding a method to a type does not add that method to the actual object. Ensure any required implementation or plugin initialization is present and tested. Keep augmentation discoverable and avoid global changes that surprise unrelated consumers. It is a tool for describing real extended behavior, not a way to invent members because the compiler reports them missing.
112. How would you reason about decorators across TypeScript configurations?
Identify whether the project uses the legacy experimental decorator model or the newer supported decorator semantics, along with relevant compiler and framework requirements. Their signatures, capabilities, metadata behavior, and emit are not interchangeable. Avoid copying an example from one mode into another without checking assumptions. Decorators can affect runtime behavior, so static type compatibility alone is insufficient. Verify the actual framework integration and generated code, and document version dependencies rather than treating all decorator syntax as one stable mechanism.
113. How would you avoid accidental global declarations?
Understand whether a file is treated as a script or module under the effective configuration and how ambient declarations enter the program. A declaration intended for one module can pollute the global namespace if placed incorrectly. Use appropriate module boundaries and targeted declarations, then inspect included files and type packages when unexpected names appear. Adding export syntax may change the declaration's meaning, so make the change deliberately. Global availability in the editor does not prove that the corresponding runtime value exists.
114. How would you investigate duplicate type identities from dependencies?
Inspect the resolved dependency graph, package versions, and the declarations contributing nominal-like members such as private fields or unique symbols. Structurally similar types can still be incompatible when their identity-sensitive parts originate from different declarations. Align dependencies or redesign the exposed boundary where appropriate rather than force a double assertion. A minimal consumer reproduction helps distinguish a legitimate mismatch from a packaging defect. The goal is consistent public contracts, not simply eliminating a confusing error message.
115. How would you design types for serialized data?
Model the representation that actually crosses the boundary, accounting for values that JSON or another format changes or cannot represent directly. Dates, undefined properties, bigint values, and class instances require deliberate treatment. A class instance type is not automatically the type of its parsed serialized form. Define conversion and validation separately and test round trips where required. The type should describe the wire contract rather than assume serialization preserves prototypes, methods, or every JavaScript value unchanged.
116. How would you decide whether an advanced type utility is worth keeping?
Compare the errors it prevents and inference it preserves with its complexity, checking cost, and burden on maintainers. A clever utility that produces unreadable diagnostics may be less useful than a few explicit domain types. Test realistic consumers and explain the invariant in plain language. Keep the implementation only if the team can maintain and validate it. Type-level sophistication is not an objective by itself; it should support a clearer and more dependable API.
117. How would you review a type guard during a security-sensitive code review?
Check every promised property, nested value, and relevant domain constraint against the actual implementation. Consider null, arrays, inherited properties, unexpected numeric values, and extra keys according to the required contract. Verify that the guard is not being mistaken for authorization or safe rendering. Test adversarial and malformed inputs in a suitable environment. The predicate's declared type is trusted by downstream code, so a small omission can spread an unsupported assumption across otherwise strictly checked modules.
118. How would you design a practical TypeScript interview exercise?
Provide a small API with unknown input, an ambiguous optional-field model, and a consumer that performs an unsafe operation. Ask the candidate to improve the types and runtime boundary, explain trade-offs, and propose positive and negative tests. Include a module or configuration assumption if relevant to the role. Strong candidates distinguish what the compiler can establish from what runtime validation must prove. If no compiler is available, label the exercise static review rather than claiming the code was type-checked.
119. What evidence would you collect before declaring a TypeScript migration successful?
Confirm that the intended files and boundaries are checked with the agreed configuration and compiler version, important runtime behavior remains correct, and public consumers still work. Review remaining any usage, assertions, suppressions, and unvalidated inputs with explicit ownership. Verify emitted artifacts and deployment paths rather than only editor diagnostics. Measure maintainability and defect-prevention outcomes where possible. Renamed files and a successful transpilation step are progress signals, not sufficient evidence that meaningful type safety has been established.
120. What does strong TypeScript engineering look like in practice?
It uses types to express real relationships and make invalid usage harder, while preserving a clear understanding of JavaScript execution. Engineers validate external data, keep assertions justified, design usable public contracts, and align configuration with the runtime and build tools. They test behavior and important type relationships separately and understand the language's intentional limits. The result is maintainable code with fewer unsupported assumptions, not maximum type complexity or a claim that successful checking proves the program cannot fail.
TypeScript Documentation and Further Reading
Use these official references for the actual compiler version, configuration, and host. Type-level relationships, emitted JavaScript, runtime APIs, and package resolution are distinct concerns. A clean type check supports the declared model; it does not replace runtime validation, behavioral tests, or authorization.
Similar Posts
